$match
The $match stage in MongoDB's aggregation pipeline is used for filtering documents to pass only those that meet certain conditions to the next stage in the pipeline. It's similar to the WHERE clause in SQL queries. The $match stage can significantly reduce the number of documents that have to be examined in subsequent stages of the pipeline, thereby improving performance.
Basic Syntax
The basic syntax of the $match stage is as follows:
db.collection.aggregate([
{
$match: { <query> }
}
]);
Here, <query> is a query condition that specifies which documents to include.
Examples
Simple Matching
To filter documents where the field status is "A":
db.orders.aggregate([
{
$match: { status: "A" }
}
]);
Using Logical Operators
You can also use logical operators like $or, $and, $not, etc. For example, to filter documents where status is either "A" or "B":
db.orders.aggregate([
{
$match: {
$or: [ { status: "A" }, { status: "B" } ]
}
}
]);
Using Comparison Operators
Comparison operators like $gt, $lt, $gte, $lte, etc., can also be used. For example, to filter documents where amount is greater than 50:
db.orders.aggregate([
{
$match: { amount: { $gt: 50 } }
}
]);
Considerations
-
Order in Pipeline: It's often beneficial to place
$matchas early as possible in the aggregation pipeline, as it reduces the number of documents that later stages have to process. -
Index Utilization: The
$matchstage can take advantage of standard MongoDB indexes, which can result in performance improvements. -
Combining with Other Stages:
$matchis commonly used in combination with stages like$group,$sort, and$projectto perform more complex queries. -
Limitations: While
$matchis powerful, it does have some limitations. For example, it can't perform text searches or use the$whereoperator. For text searches, you can use the$textstage.