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
MongoDB query to get only specific fields in nested array documents?
To get only specific fields in nested array documents in MongoDB, use $filter with $project in an aggregation pipeline to match conditions and extract required data from deeply nested arrays.
Syntax
db.collection.aggregate([
{
$project: {
"field": {
$filter: {
input: "$arrayField",
cond: { $eq: ["$$this.fieldName", "value"] }
}
}
}
}
]);
Sample Data
db.demo342.insertOne({
"Id": "101",
"details1": {
"details2": [
{
"details3": [
{
"Name": "Mike",
"CountryName": "US"
},
{
"Name": "David",
"CountryName": "AUS"
},
{
"Name": "Bob",
"CountryName": "UK"
}
]
}
]
}
});
{
"acknowledged": true,
"insertedId": ObjectId("5e53ef99f8647eb59e5620a9")
}
Verify Sample Data
db.demo342.find();
{
"_id": ObjectId("5e53ef99f8647eb59e5620a9"),
"Id": "101",
"details1": {
"details2": [
{
"details3": [
{ "Name": "Mike", "CountryName": "US" },
{ "Name": "David", "CountryName": "AUS" },
{ "Name": "Bob", "CountryName": "UK" }
]
}
]
}
}
Example: Filter Nested Array by Name
Get only documents where Name equals "Bob" from the deeply nested array ?
db.demo342.aggregate([
{
"$project": {
"details1": {
"details2": {
"$filter": {
"input": {
"$map": {
"input": "$details1.details2",
"in": {
"details3": {
"$filter": {
"input": "$$this.details3",
"cond": { "$eq": ["$$this.Name", "Bob"] }
}
}
}
}
},
"cond": { "$ne": ["$$this.details3", []] }
}
}
}
}
}
]);
{
"_id": ObjectId("5e53ef99f8647eb59e5620a9"),
"details1": {
"details2": [
{
"details3": [
{ "Name": "Bob", "CountryName": "UK" }
]
}
]
}
}
How It Works
-
$mapprocesses each element in the details2 array - Inner
$filtermatches documents where Name equals "Bob" - Outer
$filterremoves empty arrays using$necondition -
$$thisrefers to the current element being processed
Conclusion
Use nested $filter operators with $map to extract specific documents from deeply nested arrays. This approach preserves the original document structure while showing only matching elements.
Advertisements
