Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Extract particular element in MongoDB within a Nested Array?
To extract particular elements in MongoDB within nested arrays, use the $elemMatch operator to match array elements and projection to return only specific fields from the matched documents.
Syntax
db.collection.find(
{
"arrayField": {
$elemMatch: {
"nestedArrayField": {
$elemMatch: { "field": "value" }
}
}
}
},
{ "projection.field": 1 }
);
Sample Data
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 }
Example: Extract Friend Name "Robert"
Find documents where a user has a friend named "Robert" and project only the friend names ?
db.particularElementDemo.find(
{
"UserDetails": {
$elemMatch: {
"UserOtherDetails": {
$elemMatch: {
"UserFriendName": { $elemMatch: { "Name": "Robert" } }
}
}
}
}
},
{ "UserDetails.UserOtherDetails.UserFriendName.Name": 1 }
);
{
"_id": 100,
"UserDetails": [
{
"UserOtherDetails": [
{ "UserFriendName": [ { "Name": "Chris" } ] },
{ "UserFriendName": [ { "Name": "Robert" } ] }
]
}
]
}
Key Points
-
$elemMatchis used for each level of nested arrays to match specific elements. - Projection with dot notation extracts only the required fields from matched documents.
- Multiple nested
$elemMatchoperators handle deeply nested array structures.
Conclusion
Use nested $elemMatch operators to query deeply nested arrays and projection to extract specific elements. This approach efficiently filters and returns only the relevant data from complex nested structures.
Advertisements
