 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB query to filter by several array elements?
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 }    ] }Advertisements
 