Promote subfields to top level in projection without listing all keys in MongoDB?

To promote subfields to top level in projection without listing all keys in MongoDB, use $replaceRoot with $arrayToObject and $objectToArray operators. This technique flattens nested objects by converting them to arrays and reconstructing them at the root level.

Syntax

db.collection.aggregate([
    {
        "$replaceRoot": {
            "newRoot": {
                "$arrayToObject": {
                    "$concatArrays": [
                        [{ "k": "topLevelField", "v": "$topLevelField" }],
                        { "$objectToArray": "$nestedObject" }
                    ]
                }
            }
        }
    }
]);

Sample Data

db.promoteSubfieldsDemo.insertOne({
    "s": 10,
    "y": {
        "t": 20,
        "u": 30
    }
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e038004190a577c668b55d5")
}

Verify Sample Data

db.promoteSubfieldsDemo.find().pretty();
{
    "_id": ObjectId("5e038004190a577c668b55d5"),
    "s": 10,
    "y": {
        "t": 20,
        "u": 30
    }
}

Example: Promote Subfields to Top Level

db.promoteSubfieldsDemo.aggregate([
    {
        "$replaceRoot": {
            "newRoot": {
                "$arrayToObject": {
                    "$concatArrays": [
                        [{ "k": "s", "v": "$s" }],
                        { "$objectToArray": "$y" }
                    ]
                }
            }
        }
    }
]);
{ "s": 10, "t": 20, "u": 30 }

How It Works

  • $objectToArray converts the nested object y into key-value pairs: [{"k": "t", "v": 20}, {"k": "u", "v": 30}]
  • $concatArrays combines the top-level field s with the converted nested fields
  • $arrayToObject reconstructs the combined array back into a flat object
  • $replaceRoot replaces the document root with the flattened structure

Conclusion

Use $replaceRoot with $arrayToObject and $objectToArray to dynamically promote nested subfields to the top level without explicitly listing each key. This approach automatically flattens any nested object structure.

Updated on: 2026-03-15T01:45:40+05:30

226 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements