How to move an array of embedded documents up to parent and change key/value with aggregation pipeline?

Use $replaceRoot in MongoDB aggregation to move array elements up to the parent level and transform key/value pairs. The $replaceRoot stage replaces the input document with a new document structure.

Syntax

db.collection.aggregate([
    {
        $replaceRoot: {
            newRoot: {
                $mergeObjects: [
                    { _id: "$_id" },
                    { $arrayToObject: { $map: { 
                        input: "$arrayField", 
                        in: [ "$$this.keyField", "$$this.valueField" ] 
                    }}}
                ]
            }
        }
    }
]);

Sample Data

db.demo733.insertOne({
    "SubjectDetails": [
        {
            "SubjectName": "MongoDB",
            "Marks": 85
        },
        {
            "SubjectName": "MySQL",
            "Marks": 90
        },
        {
            "SubjectName": "PL/SQL",
            "Marks": 98
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5eac6e6156e85a39df5f6342")
}

Example

Transform the embedded SubjectDetails array into key-value pairs at the parent level ?

db.demo733.aggregate([
    {
        $replaceRoot: {
            newRoot: {
                $mergeObjects: [
                    { _id: "$_id" },
                    { $arrayToObject: { $map: { 
                        input: "$SubjectDetails", 
                        in: [ "$$this.SubjectName", "$$this.Marks" ] 
                    }}}
                ]
            }
        }
    }
]);
{
    "_id": ObjectId("5eac6e6156e85a39df5f6342"),
    "MongoDB": 85,
    "MySQL": 90,
    "PL/SQL": 98
}

How It Works

  • $map transforms each array element into a key-value pair using SubjectName as key and Marks as value
  • $arrayToObject converts the mapped array into an object with dynamic field names
  • $mergeObjects combines the original _id with the transformed object
  • $replaceRoot replaces the entire document with the new structure

Conclusion

The $replaceRoot aggregation stage combined with $arrayToObject and $map effectively flattens array structures into parent-level key-value pairs, creating dynamic field names from embedded document values.

Updated on: 2026-03-15T03:53:04+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements