Working with Aggregation to match all the values in MongoDB


To match all the values in MongoDB, use $match along with $and in Aggregation. Let us create a collection with documents −

> db.demo574.insertOne(
...    {
...       "details1": {
...          "details2": {
...             "dueDate": new ISODate("2020-01-10"),
...             "Name": "Chris",
...
...             "UserInformation": {
...                "Name": "John",
...                "Marks": 78
...             },
...             CountryName:"US"
...          },
...          id:101
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9167f3581e9acd78b427f6")
}

Display all documents from a collection with the help of find() method −

> db.demo574.find();

This will produce the following output −

{
   "_id" : ObjectId("5e9167f3581e9acd78b427f6"), "details1" :
   { "details2" : { "dueDate" : ISODate("2020-01-10T00:00:00Z"), "Name" : "Chris", "UserInformation" :
   { "Name" : "John", "Marks" : 78 }, "CountryName" : "US" }, "id" : 101 }
}

Following is the query to work with aggregation and match −

> db.demo574.aggregate({
...    $match: {
...       $and: [
...          {"details1.id": 101},
...          {"details1.details2.UserInformation.Name": 'John'},
...          {"details1.details2.Name": 'Chris'}
...       ]
...    }
... }
... );

This will produce the following output −

{
   "_id" : ObjectId("5e9167f3581e9acd78b427f6"), "details1" :
   { "details2" : { "dueDate" : ISODate("2020-01-10T00:00:00Z"), "Name" : "Chris", "UserInformation" :
   { "Name" : "John", "Marks" : 78 }, "CountryName" : "US" }, "id" : 101 } 
}

Updated on: 15-May-2020

406 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements