- Reference >
- Operators >
- Aggregation Pipeline Stages >
- $match (aggregation)
$match (aggregation)¶
On this page
Definition¶
-
$match¶ Filters the documents to pass only the documents that match the specified condition(s) to the next pipeline stage.
The
$matchstage has the following prototype form:$matchtakes a document that specifies the query conditions. The query syntax is identical to the read operation query syntax; i.e.$matchdoes not accept raw aggregation expressions. Instead, use a$exprquery expression to include aggregation expression in$match.
Behavior¶
Pipeline Optimization¶
- Place the
$matchas early in the aggregation pipeline as possible. Because$matchlimits the total number of documents in the aggregation pipeline, earlier$matchoperations minimize the amount of processing down the pipe. - If you place a
$matchat the very beginning of a pipeline, the query can take advantage of indexes like any otherdb.collection.find()ordb.collection.findOne().
Restrictions¶
The
$matchquery syntax is identical to the read operation query syntax; i.e.$matchdoes not accept raw aggregation expressions. To include aggregation expression in$match, use a$exprquery expression:You cannot use
$wherein$matchqueries as part of the aggregation pipeline.You cannot use
$nearor$nearSpherein$matchqueries as part of the aggregation pipeline. As an alternative, you can either:- Use
$geoNearstage instead of the$matchstage. - Use
$geoWithinquery operator with$centeror$centerSpherein the$matchstage.
- Use
To use
$textin the$matchstage, the$matchstage has to be the first stage of the pipeline.Views do not support text search.
Examples¶
The examples use a collection named articles with the following
documents:
Equality Match¶
The following operation uses $match to perform a
simple equality match:
The $match selects the documents where the author
field equals dave, and the aggregation returns the following:
Perform a Count¶
The following example selects documents to process using the
$match pipeline operator and then pipes the results
to the $group pipeline operator to compute a count of
the documents:
In the aggregation pipeline, $match selects the documents
where either the score is greater than 70 and less than 90
or the views is greater than or equal to 1000. These documents
are then piped to the $group to perform a count. The
aggregation returns the following: