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 projection on specific nested properties?
To project specific nested properties in MongoDB, use the aggregation pipeline with $addFields, $objectToArray, $filter, and $arrayToObject operators to selectively include nested fields based on conditions.
Syntax
db.collection.aggregate([
{ "$addFields": {
"nested.path": {
"$arrayToObject": {
"$filter": {
"input": { "$objectToArray": "$nested.path" },
"as": "item",
"cond": { "condition": ["$$item.k", "value"] }
}
}
}
}}
]);
Sample Data
db.demo379.insertOne({
"details1": {
"details2": {
"details3": {
"10": "John",
"50": "Chris",
"40": "David",
"30": "Mike"
}
}
}
});
{
"acknowledged": true,
"insertedId": ObjectId("5e5a94f82ae06a1609a00b10")
}
View Complete Document
db.demo379.find().pretty();
{
"_id": ObjectId("5e5a94f82ae06a1609a00b10"),
"details1": {
"details2": {
"details3": {
"10": "John",
"30": "Mike",
"40": "David",
"50": "Chris"
}
}
}
}
Example: Project Fields with Keys Between 35-60
db.demo379.aggregate([
{ "$addFields": {
"details1.details2.details3": {
"$arrayToObject": {
"$filter": {
"input": { "$objectToArray": "$details1.details2.details3" },
"as": "out",
"cond": {
"$and": [
{ "$gte": ["$$out.k", "35"] },
{ "$lte": ["$$out.k", "60"] }
]
}
}
}
}
}}
]);
{
"_id": ObjectId("5e5a94f82ae06a1609a00b10"),
"details1": {
"details2": {
"details3": {
"40": "David",
"50": "Chris"
}
}
}
}
How It Works
-
$objectToArrayconverts the nested object into an array of key-value pairs -
$filterapplies conditions to select specific key-value pairs -
$arrayToObjectconverts the filtered array back to an object -
$addFieldsreplaces the original nested field with the filtered result
Conclusion
Use aggregation pipeline operators to project specific nested properties by converting objects to arrays, filtering based on conditions, and converting back to objects. This approach provides flexible control over nested field selection.
Advertisements
