$match (Aggregation) in MongoDB with example


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

Syntax:


Aggregate[{$match:{query}}]


For Example, I am creating a "Users" collection in the "Test" database. See the 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 the 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.

No comments:

Post a Comment

Please do not enter any spam link in the comment box.

Related Posts

What is the Use of isNaN Function in JavaScript? A Comprehensive Explanation for Effective Input Validation

In the world of JavaScript, input validation is a critical aspect of ensuring that user-provided data is processed correctly. One indispensa...