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 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 } }Advertisements