Extract a particular element from a nested array with the help of dot(.) notation. Let us first create a collection with documents −
> db.extractParticularElementDemo.insertOne(
... {
... "_id" : 101,
... "StudentName" : "John",
... "StudentInformation" : [
... {
... "Age" : 21,
... "StudentPersonalInformation" : [
... {
... "StudentNickName" : "Mike",
... "StudentFamilyDetails" : [
... {
... "FatherName" : "Carol"
... }
... ]
... },
... {
... "StudentAnotherName" : "David",
... "StudentFamilyDetails" : [
... {
... "FatherName" : "Robert"
... }
... ]
... }
... ]
... }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : 101 }Following is the query to display all documents from a collection with the help of find() method −
> db.extractParticularElementDemo.find().pretty();
This will produce the following output −
{
"_id" : 101,
"StudentName" : "John",
"StudentInformation" : [
{
"Age" : 21,
"StudentPersonalInformation" : [
{
"StudentNickName" : "Mike",
"StudentFamilyDetails" : [
{
"FatherName" : "Carol"
}
]
},
{
"StudentAnotherName" : "David",
"StudentFamilyDetails" : [
{
"FatherName" : "Robert"
}
]
}
]
}
]
}Following is the query to extract particular element from a nested array −
> db.extractParticularElementDemo.find(
... {'StudentInformation.StudentPersonalInformation.StudentFamilyDetails.FatherName':'Carol'},
... {'StudentInformation.StudentPersonalInformation.StudentFamilyDetails.FatherName':1,"_id":0}
... ).pretty();This will produce the following output −
{
"StudentInformation" : [
{
"StudentPersonalInformation" : [
{
"StudentFamilyDetails" : [
{
}
"FatherName" : "Carol"
]
},
{
"StudentFamilyDetails" : [
{
"FatherName" : "Robert"
}
]
}
]
}
]
}