MongoDB query to filter by several array elements?

MongoDBDatabaseBig Data Analytics

To filter by several array elements, use $elemMatch. Let us create a collection with documents −

> db.demo87.insertOne(
...    {
...       id:101,
...       "Details": [
...          {
...             "EmployeeName": "Chris",
...             "Salary": 45000
...          },
...          {
...             "EmployeeName": "David",
...             "Salary": 50000
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2c113871bf0181ecc422ab")
}
> db.demo87.insertOne(
... {
...    id:102,
...    "Details": [
...       {
...          "EmployeeName": "Chris",
...          "Salary": 65000
...       },
...       {
...          "EmployeeName": "Mike",
...          "Salary": 100000
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2c114371bf0181ecc422ac")
}

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

> db.demo87.find();

This will produce the following output −

{
   "_id" : ObjectId("5e2c113871bf0181ecc422ab"), "id" : 101, "Details" : [
      { "EmployeeName" : "Chris", "Salary" : 45000 },
      { "EmployeeName" : "David", "Salary" : 50000 }
   ]
}
{
   "_id" : ObjectId("5e2c114371bf0181ecc422ac"), "id" : 102, "Details" : [
      { "EmployeeName" : "Chris", "Salary" : 65000 },
      { "EmployeeName" : "Mike", "Salary" : 100000 }
   ]
}

Following is the query to filter by several array elements −

> db.demo87.find({ Details: { $elemMatch: { "EmployeeName": 'Chris', "Salary": 65000 }}});

This will produce the following output −

{
   "_id" : ObjectId("5e2c114371bf0181ecc422ac"), "id" : 102, "Details" : [
      { "EmployeeName" : "Chris", "Salary" : 65000 },
      { "EmployeeName" : "Mike", "Salary" : 100000 }
   ] 
}
raja
Published on 30-Mar-2020 08:54:05
Advertisements