 
  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
MongoDB query to match documents that contain an array field
To match documents that contain an array field, use the $elemMatch operator. Let us create a collection with documents −
> db.demo592.insertOne( ...    { ...       "id":101, ...       "details" : [ ...          { "Name" : "Chris", "Value" : "200"}, ...          {"Name" : "David", "Value" : "800"} ...       ] ...    } ... ); {    "acknowledged" : true,    "insertedId" : ObjectId("5e930d8ffd2d90c177b5bcd6") } > db.demo592.insertOne( ... { ...    id:102, ...    "details" : [ ...       { "Name" : "Chris", "Value" : "500"}, ...       {"Name" : "David", "Value" : "900"} ...    ] ... } ... ); {    "acknowledged" : true,    "insertedId" : ObjectId("5e930d90fd2d90c177b5bcd7") } Display all documents from a collection with the help of find() method −
> db.demo592.find();
This will produce the following output −
{ "_id" : ObjectId("5e930d8ffd2d90c177b5bcd6"), "id" : 101, "details" : [    { "Name" : "Chris", "Value" : "200" },    { "Name" : "David", "Value" : "800" } ] } { "_id" : ObjectId("5e930d90fd2d90c177b5bcd7"), "id" : 102, "details" : [    { "Name" : "Chris", "Value" : "500" },    { "Name" : "David", "Value" : "900" } ] } Following is the query to match −
> db.demo592.find( ...    { ...       "$and" : [ ...          { "details" : { "$elemMatch" : { "Name" : "Chris", "Value" : { "$gte" : "500" } } } }, ...          { "details" : { "$elemMatch" : { "Name" : "David", "Value" : { "$gte" : "600" } } } } ...       ] ...    } ... ); This will produce the following output −
{ "_id" : ObjectId("5e930d90fd2d90c177b5bcd7"), "id" : 102, "details" : [    { "Name" : "Chris", "Value" : "500" }, { "Name" : "David", "Value" : "900" } ] }Advertisements
 