Tutorialspoint

1 Answer
Anvi Jain

For this, use aggregate framework with the $elemMatch operator. Let us first create a collection with documents −

> db.matchMultipleCriteriaDemo.insertOne({
   "EmployeeDetails": [
      {"EmployeeName": "Chris", "Salary": 45000, "Language":"Java"},
      {"EmployeeName": "Robert", "Salary": 41000, "Language":"Python"}
   ]
});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cea3bf0ef71edecf6a1f689")
}
> db.matchMultipleCriteriaDemo.insertOne({
   "EmployeeDetails": [
      {"EmployeeName": "David", "Salary": 55000, "Language":"C++"},
      {"EmployeeName": "Bob", "Salary": 61000, "Language":"C"}
   ]
});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cea3bf1ef71edecf6a1f68a")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.matchMultipleCriteriaDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cea3bf0ef71edecf6a1f689"),
   "EmployeeDetails" : [
      {
         "EmployeeName" : "Chris",
         "Salary" : 45000,
         "Language" : "Java"
      },
      {
         "EmployeeName" : "Robert",
         "Salary" : 41000,
         "Language" : "Python"
      }
   ]
}
{
   "_id" : ObjectId("5cea3bf1ef71edecf6a1f68a"),
   "EmployeeDetails" : [
      {
         "EmployeeName" : "David",
         "Salary" : 55000,
         "Language" : "C++"
      },
      {
         "EmployeeName" : "Bob",
         "Salary" : 61000,
         "Language" : "C"
      }
   ]
}

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

> db.matchMultipleCriteriaDemo.aggregate({ "$match": { "EmployeeDetails": { "$elemMatch": { "EmployeeName": "Bob", "Language":"C" } } }} ).pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cea3bf1ef71edecf6a1f68a"),
   "EmployeeDetails" : [
      {
         "EmployeeName" : "David",
         "Salary" : 55000,
         "Language" : "C++"
      },
      {
         "EmployeeName" : "Bob",
         "Salary" : 61000,
         "Language" : "C"
      }
   ]
}

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.