w3resource
MongoDB Tutorial

MongoDB Aggregation Stages Operator - $match

Description

The MongoDB $match operator filters the documents to pass only those documents that match the specified condition(s) to the next pipeline stage.

Syntax:

{ $match: { <query> } }

Points to remember:

  • It is very much effective if you place the $match as early as possible in the aggregation pipeline that limits the total number of documents in the aggregation pipeline.
  • When $match placed at the very beginning of a pipeline, the query can take advantage of indexes.
  • The $where can not be used in $match queries as part of the aggregation pipeline.

Sample collection empdetails

{
        "_id" : ObjectId("5541ffb465713ddc838b2dc7"),
        "emp_code" : "E005",
        "emp_name" : "Alan Hogg",
        "date_of_join" : "15/09/2013",
        "salary" : 9000,
        "deduction" : {
                "pf" : 2000,
                "pt" : 300,
                "it" : 200
        }
}
{
        "_id" : ObjectId("5542003c65713ddc838b2dc8"),
        "emp_code" : "E006",
        "emp_name" : "Karlos Mint",
        "date_of_join" : "23/05/2010",
        "salary" : 12000,
        "deduction" : {
                "pf" : 3000,
                "pt" : 300,
                "it" : 400
        }
}
{
        "_id" : ObjectId("554200a065713ddc838b2dc9"),
        "emp_code" : "E007",
        "emp_name" : "Burg Hence",
        "date_of_join" : "27/08/2011",
        "salary" : 10000,
        "deduction" : 4000
}

Example : $match - to Equality Match

The following command selects the documents where the salary field equals to 9000.

> db.empdetails.aggregate(
...     [ { $match : { salary : 9000 } } ]
... ).pretty();

Output :

{
        "_id" : ObjectId("5541ffb465713ddc838b2dc7"),
        "emp_code" : "E005",
        "emp_name" : "Alan Hogg",
        "date_of_join" : "15/09/2013",
        "salary" : 9000,
        "deduction" : {
                "pf" : 2000,
                "pt" : 300,
                "it" : 200
        }
}

Example : $match with $count

The following aggregation pipeline, $match selects the documents where the salary is greater than 9000 and less than or equal to 12000. Then sends the result for grouping with $group pipeline operator to perform a count.

db.empdetails.aggregate( [
                        { $match : { salary : { $gt : 9000, $lte : 12000 } } },
                        { $group: { _id: null, count: { $sum: 1 } } }
                       ] );

Outputp:

{ "_id" : null, "count" : 2 }

Previous: $project
Next: $redact



New Content: Composer: Dependency manager for PHP, R Programming