MongoDB Match

MongoDB provides $match operator that allows us to filter documents that match a defined set of conditions to the next pipeline stage. It filters the documents so that you can run an aggregation on a subset of documents that match a specific condition.

Syntax of $match

Here is the basic syntax used for the $match stage:

{ $match: { query } }

Here, the 'query' is the query condition. It would be beneficial to place $match at the very beginning in the aggregation pipeline because it minimizes the amount of processing down the pipe. The query can also take advantage of indexes when we have placed the $match at the beginning of the pipeline.

Example of MongoDB $match

Suppose we have the following 'students' collection -

{ "_id" : ObjectId("5b7ddc4f529cbc23546dc4c7"), "name" : "Jorz Rai", "age" : 10, "class" : "5A" }
{ "_id" : ObjectId("5b7ddf10529cbc23546dc4c8"), "name" : "Rana Soi", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4c9"), "name" : "Andy Joya", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4ca"), "name" : "Mary Soi", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4cb"), "name" : "Priska Somya", "age" : 12, "class" : "6A" }

The given statement returns only those students whose age equals 11.

	[{$match : { age: 11 }}]
mongodb match

Example of MongoDB $match with count

In the given example, the $match operator selects the documents in the 'students' collection where the value of age is equal to 11. The results are then piped to the $group operator where the count is performed.

	[{$match : { age: 11 }},
	 {$group: { _id: null, count: { $sum: 1 } } }
mongodb match count

Read more articles

General Knowledge

Learn Popular Language