- 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
MongoDB $elemMatch to match document
Let us create a collection with documents −
> db.demo313.insertOne({"_id":100,"details":[{"Name":"Chris","Age":24}]}); { "acknowledged" : true, "insertedId" : 100 } > db.demo313.insertOne({"_id":101,"details":[{"Name":"David","Age":22}]}); { "acknowledged" : true, "insertedId" : 101 } > db.demo313.insertOne({"_id":102,"details":[{"Name":"Mike","Age":25}]}); { "acknowledged" : true, "insertedId" : 102 }
Display all documents from a collection with the help of find() method −
> db.demo313.find();
This will produce the following output −
{ "_id" : 100, "details" : [ { "Name" : "Chris", "Age" : 24 } ] } { "_id" : 101, "details" : [ { "Name" : "David", "Age" : 22 } ] } { "_id" : 102, "details" : [ { "Name" : "Mike", "Age" : 25 } ] }
Following is the query to match document with $elemMatch in MongoDB −
db.demo313.find({_id:101},{details: { $elemMatch: { Age: 22 } } } );
This will produce the following output −
{ "_id" : 101, "details" : [ { "Name" : "David", "Age" : 22 } ] }
Advertisements