How to match multiple criteria inside an array with MongoDB?

MongoDBDatabaseBig Data Analytics

To match multiple criteria inside an array, use aggregate(). Let us create a collection with documents −

> db.demo84.insertOne({
...    "EmployeeDetails": [
...       {Name: 'John', Salary:45000, isMarried: true},
...       {Name: 'Chris', Salary:50000, isMarried: false}
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2c0a3471bf0181ecc422a5")
}
> db.demo84.insertOne({
...    "EmployeeDetails": [
...       {Name: 'Sam', Salary:56000, isMarried: false},
...       {Name: 'Bob', Salary:50000, isMarried: false}
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2c0a4071bf0181ecc422a6")
}

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

> db.demo84.find();

This will produce the following output −

{
   "_id" : ObjectId("5e2c0a3471bf0181ecc422a5"), "EmployeeDetails" : [
      { "Name" : "John", "Salary" : 45000, "isMarried" : true },
      { "Name" : "Chris", "Salary" : 50000, "isMarried" : false }
   ]
}
{
   "_id" : ObjectId("5e2c0a4071bf0181ecc422a6"), "EmployeeDetails" : [
      { "Name" : "Sam", "Salary" : 56000, "isMarried" : false },
      { "Name" : "Bob", "Salary" : 50000, "isMarried" : false }
   ]
}

Following is the query to match multiple criteria inside an array −

Example

> db.demo84.aggregate(
...    { "$match": {
...       "EmployeeDetails": {
...          "$elemMatch": {
...             "Name": "Chris",
...          "isMarried": false
...          }
...       }
...    }}
... );

This will produce the following output −

{
   "_id" : ObjectId("5e2c0a3471bf0181ecc422a5"), "EmployeeDetails" : [
      { "Name" : "John", "Salary" : 45000, "isMarried" : true },
      { "Name" : "Chris", "Salary" : 50000, "isMarried" : false }
   ] 
}
raja
Published on 30-Mar-2020 08:35:22
Advertisements