Navigation

Filter Incoming Queries

On this page

You can define filters on incoming queries that MongoDB Realm evaluates and applies before its initial query to your MongoDB cluster. Adding a filter to a collection allows you to control the shape of queried documents using projection filters and can improve query performance by reducing the number of documents for which Realm needs to evaluate a role.

Every filter consists of an Apply When JSON expression and a Filter Query document. When Realm receives an incoming MongoDB query, it evaluates the Apply When expression of all filters on the collection and merges the Filter Query document into the incoming query.

This guide walks through creating one or more query filters for a collection.

Info With Circle IconCreated with Sketch.Note

This guide requires a linked MongoDB Atlas data source.

1

You can create and manage query filters from the MongoDB rules screen in the Realm UI. To get to the rules screen, click Rules beneath Data Access in the left navigation menu.

2

Select the collection that you want to configure a filter for from the Rules menu then click the Filters tab. Click New Filter and enter a Name for the new filter.

3

In the Apply When input box, enter a JSON expression that defines when the filter applies to a query. If the expression evaluates to true for an incoming query, Realm adds the Filter Query parameters to the incoming query.

Filter Apply When Input Screenshot
Important With Circle IconCreated with Sketch.Important

MongoDB Realm evaluates and applies filters before it reads any documents, so you cannot use MongoDB document expansions in a filter's Apply When expression. However, you can use other expression variables, such as %%user, %%values, and %function.

4

In the Query input box, specify a document that contains additional query predicates to merge into the incoming query when the filter applies. For example, a filter that withholds documents that have a score below 20 could use the following filter query:

{ "score": { "$gt": 20 } }
Filter Query Input Screenshot
5

In the Projection input box, specify a document that contains a projection document to merge into the incoming query when the filter applies.

For example, a filter that withholds the career_stats and personal fields from documents could use the following filter projection:

{
"career_stats": 0,
"personal": 0
}
Filter Projection Input Screenshot
6

After you have configured the Filter Query and the Apply When expression, click Save. After saving, MongoDB Realm immediately begins evaluating and applying filters to incoming queries on the collection.

Give Feedback