How do I access subdocuments in MongoDB queries?


To access subdocuments in MongoDB, use find() with dot notation. Let us create a collection with documents −

> db.demo670.insertOne({
... id:101,
... "details":
... {
... Name:"Chris",
... Age:21,
... CountryName:"US",
... SubjectName:"MongoDB"
... }
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea3e31d04263e90dac943de")
}
> db.demo670.insertOne({ id:102, "details": { Name:"David", Age:22, CountryName:"UK", SubjectName:"MySQL" } } );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea3e33604263e90dac943df")
}

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

> db.demo670.find();

This will produce the following output −

{ "_id" : ObjectId("5ea3e31d04263e90dac943de"), "id" : 101, "details" : { "Name" : "Chris", "Age" : 21, "CountryName" : "US", "SubjectName" : "MongoDB" } }
{ "_id" : ObjectId("5ea3e33604263e90dac943df"), "id" : 102, "details" : { "Name" : "David", "Age" : 22, "CountryName" : "UK", "SubjectName" : "MySQL" } }

Following is the query to access subdocuments −

> db.demo670.find({"details.SubjectName":"MongoDB"},{"details.CountryName":1});7

This will produce the following output −

{ "_id" : ObjectId("5ea3e31d04263e90dac943de"), "details" : { "CountryName" : "US" } }

Updated on: 13-May-2020

676 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements