To extract the particular element in MongoDB, you can use $elemMatch operator. Let us first create a collection with documents −
> db.particularElementDemo.insertOne(
{
"GroupId" :"Group-1",
"UserDetails" : [
{
"UserName" : "John",
"UserOtherDetails" : [
{
"UserEmailId" : "[email protected]",
"UserFriendName" : [
{
"Name" : "Chris"
}
]
},
{
"UserEmailId" : "[email protected]",
"UserFriendName" : [
{
"Name" : "Robert"
}
]
}
]
}
]
}
);
{ "acknowledged" : true, "insertedId" : 100 }
> db.particularElementDemo.find().pretty();
{
"_id" : 100,
"GroupId" : "Group-1",
"UserDetails" : [
{
"UserName" : "John",
"UserOtherDetails" : [
{
"UserEmailId" : "[email protected]",
"UserFriendName" : [
{
"Name" : "Chris"
}
]
},
{
"UserEmailId" : "[email protected]",
"UserFriendName" : [
{
"Name" : "Robert"
}
]
}
]
}
]
}Display all documents from a collection with the help of find() method −
> db.particularElementDemo.find().pretty();
This will produce the following output −
{
"_id" : 100,
"GroupId" : "Group-1",
"UserDetails" : [
{
"UserName" : "John",
"UserOtherDetails" : [
{
"UserEmailId" : "[email protected]",
"UserFriendName" : [
{
"Name" : "Chris"
}
]
},
{
"UserEmailId" : "[email protected]",
"UserFriendName" : [
{
"Name" : "Robert"
}
]
}
]
}
]
}Following is the query to extract particular element in MongoDB in nested arrays −
> db.particularElementDemo.find(
{
'UserDetails':{
$elemMatch:{
'UserOtherDetails':{
$elemMatch:{
'UserFriendName':{ $elemMatch: {"Name" : "Robert" } }
}
}
}
}
},{"UserDetails.UserOtherDetails.UserFriendName.Name":1}
);This will produce the following output −
{ "_id" : 100, "UserDetails" : [ { "UserOtherDetails" : [ { "UserFriendName" : [ { "Name" : "Chris" } ] }, { "UserFriendName" : [ { "Name" : "Robert" } ] } ] } ] }