For this, use double underscore( __) in find(). Let us first create a collection with documents −
> db.nestedDemo.insertOne({"Information":{"__StudentName":"John Smith"}});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e06f39125ddae1f53b621f0")
}
> db.nestedDemo.insertOne({"Information":{"__StudentName":"John Doe"}});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e06f39e25ddae1f53b621f1")
}
> db.nestedDemo.insertOne({"Information":{"__StudentName":"Chris Brown"}});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e06f3a625ddae1f53b621f2")
}Following is the query to display all documents from a collection with the help of find() method −
> db.nestedDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e06f39125ddae1f53b621f0"),
"Information" : {
"__StudentName" : "John Smith"
}
}
{
"_id" : ObjectId("5e06f39e25ddae1f53b621f1"),
"Information" : {
"__StudentName" : "John Doe"
}
}
{
"_id" : ObjectId("5e06f3a625ddae1f53b621f2"),
"Information" : {
"__StudentName" : "Chris Brown"
}
}Here is the query to search a collection to find a nested value in one of its documents in MongoDB −
> db.nestedDemo.find({"Information.__StudentName":"John Doe"});This will produce the following output −
{ "_id" : ObjectId("5e06f39e25ddae1f53b621f1"), "Information" : { "__StudentName" : "John Doe" } }