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

Updated on: 14-May-2020

228 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements