- 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
Query nested array by more than one condition in MongoDB
To query nested array, use $elemMatch in MongoDB. Let us create a collection with documents −
> db.demo203.insertOne({ ... "_id" : "101", ... "Name" : "Chris", ... "details1" : [ ... { ... "empName" : "David", ... "salary" : "50000", ... "technology" : [ ... "MySQL", ... "MongoDB" ... ] ... }, ... { ... "empName" : "Carol", ... "salary" : "70000", ... ... "technology" : [ ... "Java", ... "Spring" ... ] ... } ... ] ...} ...); { "acknowledged" : true, "insertedId" : "101" }
Display all documents from a collection with the help of find() method −
> db.demo203.find();
This will produce the following output −
{ "_id" : "101", "Name" : "Chris", "details1" : [ { "empName" : "David", "salary" : "50000", "technology" : [ "MySQL", "MongoDB" ] }, { "empName" : "Carol", "salary" : "70000", "technology" : [ "Java", "Spring" ] } ] }
Here is how to query nested array by more than one condition −
> db.demo203.find( ... {details1: { $elemMatch:{"technology" : "MySQL", "empName":"David"}}} ... ).pretty()
This will produce the following output −
{ "_id" : "101", "Name" : "Chris", "details1" : [ { "empName" : "David", "salary" : "50000", "technology" : [ "MySQL", "MongoDB" ] }, { "empName" : "Carol", "salary" : "70000", "technology" : [ "Java", "Spring" ] } ] }
Advertisements