Nov 24, 2015

$match (Aggregation) in MongoDB with example

This operator use to filters the documents stream. If specific condition(s) match then it will allow to document to pass next pipeline.

Syntax:


Aggregate[{$match:{query}}]


For Example: I am creating "Users" collection in "Test" database. See below query.


Use Test





db.Users.insert(
{
    "fName" : "Dilip",
    "lName" : "Singh",
    "address" : "Noida",
    "totalOrder" : 150,
    "createdDate" : "2014/07/07"
})
db.Users.insert(
{
    "fName" : "Vipul",
    "lName" : "Bhatt",
    "address" : "Delhi",
    "totalOrder" : 50,
    "createdDate" : "2013/07/07"
})
db.Users.insert(
{
    "fName" : "Brijesh",
    "lName" : "Kumar",
    "address" : "Gorakhpur",
    "totalOrder" : 70,
    "createdDate" : "2012/07/07"
})
db.Users.insert(
{
    "fName" : "Raj",
    "lName" : "Kumar",
    "address" : "Bokaro",
    "totalOrder" : 40,
    "createdDate" : "2010/07/07"
})

db.Users.find()



Applying $match for filter on "fName", see below.


db.Users.aggregate(
[{
    $match:{fName:"Dilip"}
}])


output


/* 0 */
{
    "result" : [
        {
            "_id" : ObjectId("55dac0b31c949abf34d5daed"),
            "fName" : "Dilip",
            "lName" : "Singh",
            "address" : "Noida",
            "totalOrder" : 150,
            "createdDate" : "2014/07/07"
        }
    ],
    "ok" : 1
}


Note:

  • You cannot use $where in $match queries as part of the aggregation pipeline.
  • To use $text in the $match stage, the $match stage has to be the first stage of the pipeline.