$match (aggregation)

Definition

  • $match
  • Filters the documents to pass only the documents that match thespecified condition(s) to the next pipeline stage.

The $match stage has the following prototype form:

  1. { $match: { <query> } }

$match takes a document that specifies the queryconditions. The query syntax is identical to the readoperation query syntax; i.e.$match does not accept raw aggregation expressions. Instead, use a $expr queryexpression to include aggregation expression in $match.

Behavior

Pipeline Optimization

Restrictions

  1. { $match: { $expr: { <aggregation expression> } } }

Views do not support text search.

Examples

The examples use a collection named articles with the followingdocuments:

  1. { "_id" : ObjectId("512bc95fe835e68f199c8686"), "author" : "dave", "score" : 80, "views" : 100 }
  2. { "_id" : ObjectId("512bc962e835e68f199c8687"), "author" : "dave", "score" : 85, "views" : 521 }
  3. { "_id" : ObjectId("55f5a192d4bede9ac365b257"), "author" : "ahn", "score" : 60, "views" : 1000 }
  4. { "_id" : ObjectId("55f5a192d4bede9ac365b258"), "author" : "li", "score" : 55, "views" : 5000 }
  5. { "_id" : ObjectId("55f5a1d3d4bede9ac365b259"), "author" : "annT", "score" : 60, "views" : 50 }
  6. { "_id" : ObjectId("55f5a1d3d4bede9ac365b25a"), "author" : "li", "score" : 94, "views" : 999 }
  7. { "_id" : ObjectId("55f5a1d3d4bede9ac365b25b"), "author" : "ty", "score" : 95, "views" : 1000 }

Equality Match

The following operation uses $match to perform asimple equality match:

  1. db.articles.aggregate(
  2. [ { $match : { author : "dave" } } ]
  3. );

The $match selects the documents where the authorfield equals dave, and the aggregation returns the following:

  1. { "_id" : ObjectId("512bc95fe835e68f199c8686"), "author" : "dave", "score" : 80, "views" : 100 }
  2. { "_id" : ObjectId("512bc962e835e68f199c8687"), "author" : "dave", "score" : 85, "views" : 521 }

Perform a Count

The following example selects documents to process using the$match pipeline operator and then pipes the resultsto the $group pipeline operator to compute a count ofthe documents:

  1. db.articles.aggregate( [
  2. { $match: { $or: [ { score: { $gt: 70, $lt: 90 } }, { views: { $gte: 1000 } } ] } },
  3. { $group: { _id: null, count: { $sum: 1 } } }
  4. ] );

In the aggregation pipeline, $match selects the documentswhere either the score is greater than 70 and less than 90or the views is greater than or equal to 1000. These documentsare then piped to the $group to perform a count. Theaggregation returns the following:

  1. { "_id" : null, "count" : 5 }

See also

Aggregation with the Zip Code Data Set,Aggregation with User Preference Data