- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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