- 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
How to match multiple criteria inside an array with MongoDB?
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 } ] }
Advertisements