MongoDB uses the $match
stage in the aggregation pipeline to filter documents according to predetermined criteria. The $match stage in MongoDB is usually the first stage in an aggregation pipeline as it filters the documents before any other stages are executed.
You can use various operators (e.g., $eq
, $ne
, $lt
, $lte
, $gt
, $gte
, $in
, $nin
, $and
, $or
, etc.) and complex criteria in the $match
stage to tailor the filtering to your specific needs. Additionally, you can use regular expressions, $elemMatch
for array filtering, and more to create sophisticated filtering conditions.
1. Syntax of $match operator
Following is the syntax of the $match
stage.
# Syntax
db.collection.aggregate([ $match: {cond} ]);
Here,
db.collection
is the name of the MongoDB collection you want to aggregate.$match
is the first stage in the pipeline.cond
signified the condition or query to filter the documents.- Inside the
$match
stage, you specify the filtering criteria as a document with field-value pairs. Documents that match these criteria will be included in the subsequent stages of the pipeline.
Let’s begin with the example of the $match
stage where the following collection is used.
# Create Collection
db.student.insertMany([
{
_id: 1,
name: "Jimmy",
age: 25,
gender: "M",
marks: 91,
course: "MongoDB"
},
{
_id: 2,
name: "Elena",
age: 24,
gender: "F",
marks: 85,
course: "Python"
},
{
_id: 3,
name: "Emily",
age: 20,
gender: "F",
marks: 80,
course: "SQL"
},
{
_id: 4,
name: "Zack",
age: 23,
gender: "M",
marks: 90,
course: "PHP"
}
]
)
2. Using the $match operator
In MongoDB, the $match
stage is used as part of the aggregation framework, which allows you to filter documents based on specific criteria before performing further data transformation or analysis. The $match
stage is similar to the find()
method for querying documents but is typically used within an aggregation pipeline.
# $match operator for single field
db.student.aggregate( [
{ $match : { name : "Zack" } } ]);
In the above aggregation pipeline, we specifically used the $match
stage to filter documents. The $match
stage here filters the documents based on a given condition. In this case, it matches documents where the name
field equals Zack
.
The above $match
stage query results displayed the document containing the field name
with the value zack
. However, if multiple documents match the criteria, all of them will be returned.
3. Using the $match operator for multiple fields
The $match operator of the aggregation pipeline is also used to filter the document for multiple values of the field. We must call the $in
operator in the $match stage like this.
# Usage of $in operator in the $match stage
db.student.aggregate([
{ $match: { course: { $in: ["MongoDB", "SQL"] } } }])
The aggregation query of MongoDB is deployed with the $match
stage which is set with the filter to match the document. The $match
operator takes the course
field, which is specified by the $in
operator. The $in
operator is the comparison operator that selects the documents where the value of the course
field matches any of the specified values in the array [MongoDB", "SQL"
].
The results are fetched below, which display the following expected documents.
Also, if you want to learn about find() function using in ($in operator), you can use the following link.
4. Using the $match operator with the $gt and $lt operator
Sometimes the $match
stage is used with the conditional operation to match the document to specify the range. Consider the query of the $match
stage with the conditional operator of MongoDB below.
# Usage of $match operator with $gt and $lt operator
db.student.aggregate( [
{ $match : { age : { $gt : 21, $lt : 24 } } }
] );
The above pipeline of aggregation is set with the $match
stage, which matches the documents in the student collection where the age
field is greater than 21 and less than 24. The $match
stage uses two comparison operators, $gt
and $lt
, to specify the age range.
There is only one matched document in the specific range, as represented by the following results.
5. Using the $match operator with the logical operator
Moreover, using the logical operator, the $match
stage filters the documents based on multiple criteria. Follow the query below to get matched documents on the basis of the logical $or
operator.
# Usage of $match operator with logical operator
db.student.aggregate( [
{ $match: { $or: [ { marks: { $gt: 80, $lt: 90 } },
{ age: { $gte: 24 } } ] } }
] );
The aggregation query of the $match stage above filters all documents in the student collection where either the marks
field is greater than 80
and less than 90
or the age
field is greater than or equal to 24
. The $or
operator used within the $match
stage specifies multiple conditions that can be satisfied to match a document.
The documents are retrieved below from the following query execution.
6. Using the $match operator with the $group operator
It’s worth noting that pipeline aggregation has two stages at the same time. Therefore, we use the match stage and $group
stage together in this section. The $match
stage applies a certain condition to the documents. On the other hand, the $group
stage group filtered documents based on a specific field and carried out operations on each group.
# Usage of $match operator with the $group operator
db.student.aggregate([
{ $match:{ gender:'M'}},
{ $group:{ _id:'$course', totalStudent: { $sum:1 } }
}])
Above, the $match
stage first filters the documents where the gender field equals M
. Then group the filtered documents by the course field using the $group
stage, and calculate the total number of students in each course using the $sum
accumulator. The outcome shows the matched document, which is grouped below.
7. Conclusion
Wrap up here; we have now discussed MongoDB’s aggregation pipeline $match
stage with the syntax and some examples. We have used the MongoDB $match stage in combination with other operators to query documents.
Also, if you want to learn more about this topic, you can use the following link.
Related Articles
- MongoDB $elemMatch Operator Usage
- MongoDB $exists Operator – Get documents if field exists
- MongoDB $or Operator Usage
- MongoDB insertOne() & insertMany() Documents
- Upsert in MongoDB Explained with Examples
- MongoDB Realm
- Working with MongoDB Transactions
- MongoDB distinct() – Get Unique values from field
- MongoDB Delete Documents from Collection
- Install MongoDB On Ubuntu
- MongoDB $filter Operator Usage