
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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 Containing 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