How to select a specific subdocument in MongoDB?


To select a specific subdocument in MongoDB, use find(). Let us create a collection with documents −

> db.demo37.insertOne({"Details":[{"Name":"Chris","Age":21},{"Name":"David","Age":23}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e176635cfb11e5c34d898d7")
}
> db.demo37.insertOne({"Details":[{"Name":"Sam","Age":23},{"Name":"Robert","Age":25}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e17664acfb11e5c34d898d8")
}

Display all documents from a collection with the help of find() method −

> db.demo37.find();

This will produce the following output −

{ "_id" : ObjectId("5e176635cfb11e5c34d898d7"), "Details" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 23 } ] }
{ "_id" : ObjectId("5e17664acfb11e5c34d898d8"), "Details" : [ { "Name" : "Sam", "Age" : 23 }, { "Name" : "Robert", "Age" : 25 } ] }

Following is the query to select subdocument −

> db.demo37.find({'Details.Name' : 'Sam'},{_id: 0, 'Details.$.Name': 1});

This will produce the following output −

{ "Details" : [ { "Name" : "Sam", "Age" : 23 } ] }

Updated on: 02-Apr-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements