$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
$match
as early as possible in the aggregation pipeline, as it reduces the number of documents that later stages have to process.Index Utilization: The
$match
stage can take advantage of standard MongoDB indexes, which can result in performance improvements.Combining with Other Stages:
$match
is commonly used in combination with stages like$group
,$sort
, and$project
to perform more complex queries.Limitations: While
$match
is powerful, it does have some limitations. For example, it can't perform text searches or use the$where
operator. For text searches, you can use the$text
stage.