
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 embedded documents?
To query embedded documents in MongoDB, use aggregate(). Let us create a collection with documents −
> db.demo705.insertOne( ... { ... _id:101, ... "Information": ... [ ... { ... "StudentName":"Chris", ... "StudentAge":21 ... }, ... { ... "StudentName":"David", ... "StudentAge":23 ... }, ... { ... "StudentName":"Bob", ... "StudentAge":20 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 }
Display all documents from a collection with the help of find() method −
> db.demo705.find();
This will produce the following output −
{ "_id" : 101, "Information" : [ { "StudentName" : "Chris", "StudentAge" : 21 }, { "StudentName" : "David", "StudentAge" : 23 }, { "StudentName" : "Bob", "StudentAge" : 20 } ] }
Following is how to query embedded documents in MongoDB −
> db.demo705.aggregate( ... { $unwind: '$Information' }, ... { $match: {'Information.StudentAge': {$gte: 21}}}, ... { $project: {Information: 1}} ... )
This will produce the following output −
{ "_id" : 101, "Information" : { "StudentName" : "Chris", "StudentAge" : 21 } } { "_id" : 101, "Information" : { "StudentName" : "David", "StudentAge" : 23 } }
- Related Questions & Answers
- Check for existing documents/embedded documents in MongoDB
- Updating Nested Embedded Documents in MongoDB?
- Query an array of embedded documents in MongoDB and push another?
- MongoDB query to skip documents
- MongoDB query to return only embedded document?
- MongoDB query for fields in embedded document?
- Querying array of Embedded Documents in MongoDB based on Range?
- MongoDB query to add multiple documents
- MongoDB query to group duplicate documents
- Appending an entry in one to many embedded documents with MongoDB
- Filter query on array of embedded document with MongoDB?
- MongoDB query to skip n first documents?
- Filter documents in MongoDB using simple query?
- Get all embedded documents with “isMarried” status in a MongoDB collection
- Fetch multiple documents in MongoDB query with OR condition?
Advertisements