 
  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
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
 