How to Use $replaceRoot in Aggregation in MongoDB
Use the
$replaceRoot stage in a MongoDB aggregation pipeline to replace the current document with a specified subdocument. This lets you promote a nested object to the root level by specifying { newRoot: <expression> }. It is useful for reshaping documents during aggregation.Syntax
The $replaceRoot stage takes an object with a newRoot field. This field defines the new document to replace the current one in the pipeline.
{ $replaceRoot: { newRoot: <expression> } }<expression>is usually a field path to a subdocument.
This stage outputs the newRoot document as the new document for the next pipeline stage.
json
{
$replaceRoot: { newRoot: "$<fieldPath>" }
}Example
This example shows how to use $replaceRoot to promote the address subdocument to the root level in each document.
mongodb
db.users.aggregate([
{
$replaceRoot: { newRoot: "$address" }
}
])Output
[
{ "street": "123 Maple St", "city": "Springfield", "zip": "12345" },
{ "street": "456 Oak St", "city": "Shelbyville", "zip": "67890" }
]
Common Pitfalls
Common mistakes when using $replaceRoot include:
- Using a field path that does not exist or is not an object, which causes errors.
- Replacing the root with a non-object value, which is invalid.
- Confusing
$replaceRootwith$projector$addFields, which modify fields but do not replace the whole document.
Always ensure the newRoot expression points to a valid subdocument.
mongodb
/* Wrong usage: newRoot points to a string field */ db.users.aggregate([ { $replaceRoot: { newRoot: "$name" } } ]) /* Correct usage: newRoot points to a subdocument */ db.users.aggregate([ { $replaceRoot: { newRoot: "$address" } } ])
Quick Reference
| Feature | Description |
|---|---|
| $replaceRoot | Replaces the entire document with the specified subdocument. |
| newRoot | Field specifying the new root document in the pipeline. |
| Usage | Promotes nested objects to top-level for easier access or reshaping. |
| Requirement | newRoot must be an object, not a primitive value. |
| Common use case | Flattening nested documents during aggregation. |
Key Takeaways
Use $replaceRoot to replace the current document with a nested subdocument in aggregation.
The newRoot field must point to a valid object, not a primitive value.
This stage helps reshape documents by promoting nested fields to the top level.
Avoid using $replaceRoot with non-object fields to prevent errors.
It is different from $project or $addFields which modify but do not replace documents.