Retrieving an embedded object as a document via the aggregation framework in MongoDB?

To retrieve an embedded object as a document in MongoDB, use the aggregation framework's $replaceRoot stage. This operator promotes the specified embedded document to the top level, effectively replacing the entire document structure.

Syntax

db.collection.aggregate([
    { $replaceRoot: { newRoot: "$embeddedFieldName" } }
]);

Create Sample Data

db.embeddedObjectDemo.insertMany([
    {
        "UserDetails": {
            "UserName": "John",
            "UserAge": 24,
            "UserEmailId": "John22@gmail.com"
        }
    },
    {
        "UserDetails": {
            "UserName": "Carol",
            "UserAge": 26,
            "UserEmailId": "Carol123@gmail.com"
        }
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5ced580fef71edecf6a1f693"),
        ObjectId("5ced5828ef71edecf6a1f694")
    ]
}

View Original Documents

db.embeddedObjectDemo.find().pretty();
{
    "_id": ObjectId("5ced580fef71edecf6a1f693"),
    "UserDetails": {
        "UserName": "John",
        "UserAge": 24,
        "UserEmailId": "John22@gmail.com"
    }
}
{
    "_id": ObjectId("5ced5828ef71edecf6a1f694"),
    "UserDetails": {
        "UserName": "Carol",
        "UserAge": 26,
        "UserEmailId": "Carol123@gmail.com"
    }
}

Extract Embedded Objects

db.embeddedObjectDemo.aggregate([
    { $replaceRoot: { newRoot: "$UserDetails" } }
]);
{ "UserName": "John", "UserAge": 24, "UserEmailId": "John22@gmail.com" }
{ "UserName": "Carol", "UserAge": 26, "UserEmailId": "Carol123@gmail.com" }

Key Points

  • $replaceRoot completely replaces the document structure with the specified embedded object.
  • The original _id field is removed unless explicitly preserved.
  • Use $ prefix to reference field paths in the aggregation pipeline.

Conclusion

The $replaceRoot aggregation stage effectively extracts embedded objects as standalone documents. This technique is useful for flattening nested data structures and simplifying document output in MongoDB queries.

Updated on: 2026-03-15T01:36:00+05:30

354 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements