- Trending Categories
- 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 get the matching document inside an array in MongoDB?
To get the matching document, use $elemMatch. Let us first create a collection with documents −
> db.getMatchingDocumentDemo.insertOne( { _id :1, "UserDetails":[ { "UserName":"John", "UserAge":23 } ] } ); { "acknowledged" : true, "insertedId" : 1 } > db.getMatchingDocumentDemo.insertOne( { _id :2, "UserDetails":[ { "UserName":"Larry", "UserAge":24 } ] } ); { "acknowledged" : true, "insertedId" : 2 }
Following is the query to display all documents from a collection with the help of find() method −
> db.getMatchingDocumentDemo.find().pretty();
This will produce the following output −
{ "_id" : 1, "UserDetails" : [ { "UserName" : "John", "UserAge" : 23 } ] } { "_id" : 2, "UserDetails" : [ { "UserName" : "Larry", "UserAge" : 24 } ] }
Following is the query to get the matching document inside an array in MongoDB −
> db.getMatchingDocumentDemo.find({UserDetails: {$elemMatch: {UserAge: 24}}});
This will produce the following output −
{ "_id" : 2, "UserDetails" : [ { "UserName" : "Larry", "UserAge" : 24 } ] }
Advertisements