Use $unwind twice for specific embedded document in MongoDB. Let us create a collection with documents −
> db.demo631.insert( ... { ... id: "101", ... Info1: [ ... { ... CountryName : "US", ... Info2 : [ ... { ... Name:"Chris", ... Age:24 ... },{ ... ... Name:"Bob", .. . Age:22 ... } ... ] ... } ... ] ... } ... ); WriteResult({ "nInserted" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo631.find();
This will produce the following output −
{ "_id" : ObjectId("5e9b0eb16c954c74be91e6bf"), "id" : "101", "Info1" : [ { "CountryName" : "US", "Info2" : [ { "Name" : "Chris", "Age" : 24 }, { "Name" : "Bob", "Age" : 22 } ] } ] }
Following is the query to return specific MongoDB embedded document −
> db.demo631.aggregate([ ... { "$unwind": "$Info1" }, ... { "$unwind": "$Info1.Info2" }, ... { "$match": { "Info1.Info2.Age": 22 } } ... ])
This will produce the following output −
{ "_id" : ObjectId("5e9b0eb16c954c74be91e6bf"), "id" : "101", "Info1" : { "CountryName" : "US", "Info2" : { "Name" : "Bob", "Age" : 22 } } }