- Stitch >
- MongoDB Atlas >
- Reference
Query Filters¶
On this page
Overview¶
A MongoDB query filter conditionally applies additional query predicates and projections to an incoming query before Stitch runs it. Filters are useful for improving the performance of queries on collections that have many documents or roles that use complex Apply When expressions.
You can add filters to a collection to remove documents that you know are not relevant to incoming queries before Stitch evaluates any roles. This can help to reduce the amount of computation that Stitch needs to perform for a request. Filters can take advantage of indexes in a linked MongoDB cluster, so filtering out a document is generally faster than waiting for Stitch to evaluate a role for it.
Filter Application Process¶
When Stitch receives a query request, it determines if any filters
associated with the collection apply to the request and adds those to
the query. To assign filters to a query, Stitch evaluates the
Apply When JSON expression
that you defined for each filter. If a filter’s Apply When
evaluates to true
, Stitch merges the Filter Query into
the incoming query document.
Example
A collection contains several million documents and has one role with the following Apply When expression:
If no filter is applied, Stitch will evaluate a role for each
document that the query matches. We know that Stitch will withhold
any document that does not have the user’s id as the value of the
owner_id
field, so we save time and compute resources by applying
an additional query predicate that excludes those documents before
Stitch evaluates any roles:
Apply When | Query | Projection |
---|---|---|
{ "%%true": true } |
{ "owner_id": "%%user.id" } |
{} |
Query Filter Configuration¶
Field | Description |
---|---|
name String
|
Required. The name of the filter. Filter names are useful for identifying and distinguishing between filters. Limited to 100 characters or fewer. |
apply_when |
Required. A JSON expression that determines when this filter applies to a given query. Important Stitch 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 |
query Document
|
Required. A MongoDB query filter that contains additional query predicates to merge into incoming queries that the filter applies to. Example A filter that withholds documents that have a |
projection Document
|
Required. A MongoDB projection document that specifies additional field projections to merge into incoming queries that the filter applies to. Projection Conflicts MongoDB projections can be either inclusive or exclusive, i.e. they can either return only specified fields or withhold fields that are not specified. If multiple filters apply to a query, the filters must all specify the same type of projection or the query will fail. Example A filter that withholds the |