$match Aggregation in MongoDB
Overview
The match in MongoDB is used for document filtering based on certain specific criteria. We can also write multiple conditions in $match for filtering documents.
What is $match Aggregation in MongoDB?
Match in MongoDB allows document filtering based on some conditions set. Only the documents that satisfy the specified conditions will further proceed for the further stages of the pipeline.
Syntax
The syntax of the match in MongoDB has two main parameters.
- $match:
First we will write the $match operator. - {<the_query>}:
Here we will write the conditions for $match, and we will write the query similarly as we write for MongoDB documents.
Return Type:
match in MongoDB returns the array of documents that satisfy the specified condition.
Examples
Creating an example dataset:
We will take an example of the employee dataset and insert multiple documents into it using insertMany().
After executing the command, documents will be inserted in the employee collection and it will look like this:
$match with count
Below is an example of selecting documents for processing by the $match operator. And after $match, we have used $group for counting the number of documents.
In the above command, we have specified a condition that age is greater than 30 and less than 50 with $match, so it will select those documents from the employee collection that satisfy the condition. Then $group operator is used for the pipelining of those documents to perform a count on them. So will get the following output by executing the above command:
$match with equality match:
Here we are using the equality operator with $match for specifying the condition. This will simply select the documents having the male gender.
The above query will give the following output:
Here we can see that $match has selected all the documents having the male gender.
FAQs
Q: Can multiple conditions be used within a single?
A: Yes multiple conditions can be used within the single match in Mongodb. All the conditions are implicitly treated with the AND operator.
Q: Can be write comparison operators such as $gt, $lt, $gte, etc. with match in MongoDB?
A: Yes we can use comparison operators in $match for writing the complex filtering conditions.
Conclusion
- $match in MongoDB allows document filtering based on some conditions set.
- {$match: {<the_query>}} is the syntax of match in mongodb.
- match in MongoDB returns the array of documents that satisfy the specified condition.
- We can use write comparison operators such as $gt, $lt, $gte, etc. with match in MongoDB
- We can write multiple conditions in $match for filtering of documents.