- 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 find a certain element in the MongoDB embedded document?
To find a certain element, use $project in MongoDB. Let us create a collection with documents −
> db.demo744.insertOne( ... { ... studentInformation: ... [ ... { ... studentName:"Robert", ... grade:"A" ... }, ... { ... studentName:"Bob", ... grade:"C" ... }, ... { ... studentName:"John", ... grade:"B" ... }, ... { ... studentName:"Sam", ... grade:"A" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ead928a57bb72a10bcf0684") }
Display all documents from a collection with the help of find() method −
> db.demo744.find();
This will produce the following output −
{ "_id" : ObjectId("5ead928a57bb72a10bcf0684"), "studentInformation" : [ { "studentName" : "Robert", "grade" : "A" }, { "studentName" : "Bob", "grade" : "C" }, { "studentName" : "John", "grade" : "B" }, { "studentName" : "Sam", "grade" : "A" } ] }
Following is the query to find a certain element in the embedded document −
> db.demo744.aggregate( ... { $unwind: '$studentInformation' }, ... { $match: {'studentInformation.grade':"A"}}, ... { $project: {"studentInformation.studentName": 1}} ... )
This will produce the following output −
{ "_id" : ObjectId("5ead928a57bb72a10bcf0684"), "studentInformation" : { "studentName" : "Robert" } } { "_id" : ObjectId("5ead928a57bb72a10bcf0684"), "studentInformation" : { "studentName" : "Sam" } }
Advertisements
To Continue Learning Please Login
Login with Google