Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extract particular element in MongoDB within a Nested Array?
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" : "John123@gmail.com",
"UserFriendName" : [
{
"Name" : "Chris"
}
]
},
{
"UserEmailId" : "John22@hotmail.com",
"UserFriendName" : [
{
"Name" : "Robert"
}
]
}
]
}
]
}
);
{ "acknowledged" : true, "insertedId" : 100 }
> db.particularElementDemo.find().pretty();
{
"_id" : 100,
"GroupId" : "Group-1",
"UserDetails" : [
{
"UserName" : "John",
"UserOtherDetails" : [
{
"UserEmailId" : "John123@gmail.com",
"UserFriendName" : [
{
"Name" : "Chris"
}
]
},
{
"UserEmailId" : "John22@hotmail.com",
"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" : "John123@gmail.com",
"UserFriendName" : [
{
"Name" : "Chris"
}
]
},
{
"UserEmailId" : "John22@hotmail.com",
"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" } ] } ] } ] }Advertisements