- 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 filter documents based on an array in MongoDB?
To filter documents based on an array, use $elemMatch. The $elemMatch operator matches documents that contain an array field.
Let us create a collection with documents −
> db.demo453.insertOne( ... { _id: 101, details: [ { Name: "David", Marks: 60 }, { Name: "Mike", Marks: 55} ] } ... ) { "acknowledged" : true, "insertedId" : 101 } > db.demo453.insertOne( ... { _id: 102, details: [ { Name: "Bob", Marks: 80 }, { Name: "Sam", Marks: 78} ] } ... ) { "acknowledged" : true, "insertedId" : 102 } > db.demo453.insertOne( ... { _id: 103, details: [ { Name: "Carol", Marks: 67 }, { Name: "John", Marks: 79} ] } ... ) { "acknowledged" : true, "insertedId" : 103 }
Display all documents from a collection with the help of find() method −
> db.demo453.find();
This will produce the following output −
{ "_id" : 101, "details" : [ { "Name" : "David", "Marks" : 60 }, { "Name" : "Mike", "Marks" : 55 } ] } { "_id" : 102, "details" : [ { "Name" : "Bob", "Marks" : 80 }, { "Name" : "Sam", "Marks" : 78 } ] } { "_id" : 103, "details" : [ { "Name" : "Carol", "Marks" : 67 }, { "Name" : "John", "Marks" : 79 } ] }
Following is the query to filter documents based on an array −
> db.demo453.find( ... { details: { $elemMatch: {Marks: { $gte: 75 } } } } ... )
This will produce the following output −
{ "_id" : 102, "details" : [ { "Name" : "Bob", "Marks" : 80 }, { "Name" : "Sam", "Marks" : 78 } ] } { "_id" : 103, "details" : [ { "Name" : "Carol", "Marks" : 67 }, { "Name" : "John", "Marks" : 79 } ] }
Advertisements