- Reference >
- Operators >
- Aggregation Pipeline Operators >
- Pipeline Aggregation Stages >
- $match (aggregation)
$match (aggregation)¶
Definition¶
- $match¶
Filters the documents to pass only the documents that match the specified condition(s) to the next pipeline stage.
The $match stage has the following prototype form:
{ $match: { <query> } }
$match takes a document that specifies the query conditions. The query syntax is identical to the read operation query syntax.
Behavior¶
Pipeline Optimization¶
- Place the $match as early in the aggregation pipeline as possible. Because $match limits the total number of documents in the aggregation pipeline, earlier $match operations minimize the amount of processing down the pipe.
- If you place a $match at the very beginning of a pipeline, the query can take advantage of indexes like any other db.collection.find() or db.collection.findOne().
Examples¶
Equality Match¶
The following operation uses $match to perform a simple equality match:
db.articles.aggregate(
[ { $match : { author : "dave" } } ]
);
The $match selects the documents where the author field equals dave, and the aggregation returns the following:
{
"result" : [
{
"_id" : ObjectId("512bc95fe835e68f199c8686"),
"author": "dave",
"score" : 80
},
{ "_id" : ObjectId("512bc962e835e68f199c8687"),
"author" : "dave",
"score" : 85
}
],
"ok" : 1
}
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:
db.articles.aggregate( [
{ $match : { score : { $gt : 70, $lte : 90 } } },
{ $group: { _id: null, count: { $sum: 1 } } }
] );
In the aggregation pipeline, $match selects the documents where the score is greater than 70 and less than or equal to 90. These documents are then piped to the $group to perform a count. The aggregation returns the following:
{
"result" : [
{
"_id" : null,
"count" : 3
}
],
"ok" : 1
}