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

  • $objectToArray converts the nested object into an array of key-value pairs
  • $filter applies conditions to select specific key-value pairs
  • $arrayToObject converts the filtered array back to an object
  • $addFields replaces 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.

Updated on: 2026-03-15T02:44:32+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements