MongoDB find() query for nested document?



To fetch a value from the nested document, use dot notation. Let us create a collection with documents −

> db.demo591.insert([ ...    { "Name": "John", "Age": 23 }, ...    {"Name": "Carol", "Age": 26}, ...    { "Name": "Robert", "Age": 29, ...    details:[ ...       { ...          Email:"Robert@gmail.com",CountryName:"US"},{"Post":35} ...       ]} ... ]); BulkWriteResult({    "writeErrors" : [ ],    "writeConcernErrors" : [ ],    "nInserted" : 3,    "nUpserted" : 0,    "nMatched" : 0,    "nModified" : 0,    "nRemoved" : 0,    "upserted" : [ ] })

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

> db.demo591.find();

This will produce the following output −

{ "_id" : ObjectId("5e92dd08fd2d90c177b5bcd3"), "Name" : "John", "Age" : 23 } { "_id" : ObjectId("5e92dd08fd2d90c177b5bcd4"), "Name" : "Carol", "Age" : 26 } { "_id" : ObjectId("5e92dd08fd2d90c177b5bcd5"), "Name" : "Robert", "Age" : 29, "details" : [ { "Email" : "Robert@gmail.com", "CountryName" : "US" }, { "Post" : 35 } ] }

Following is the query to fetch nested document using dot notation −

> db.demo591.find({"details.Email": "Robert@gmail.com"});

This will produce the following output −

{ "_id" : ObjectId("5e92dd08fd2d90c177b5bcd5"), "Name" : "Robert", "Age" : 29, "details" : [    { "Email" : "Robert@gmail.com", "CountryName" : "US" }, { "Post" : 35 } ] }
Updated on: 2020-05-15T06:52:22+05:30

694 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements