$replaceRoot (Replace Root)
Last updated: 2026-10-09
$replaceRoot (Replace Root)
$replaceRoot replaces the entire document with a specified embedded document, commonly used to promote a nested object like detail to the top level. All original fields are lost. It errors when the target is missing or not an object; guard with $ifNull or use $replaceWith, which keeps the document when the result is null.
| Category | Core Stages |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $replaceRoot: { newRoot: <document expression> } }
⚙️ Parameters
| newRoot | Expression evaluated to become the new document; must be an object. |
|---|
Returns:Document stream rooted at newRoot
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $replaceRoot: promote detail to the root
db.orders.aggregate([
{ $replaceRoot: { newRoot: '$detail' } }
])
Output:
// Original order fields gone; only detail remains
{ "city": "SH", "zip": "200000" }
📌 Notes
- newRoot must evaluate to an object or the stage errors
- Original fields are fully replaced; merge what you need with $set first
- $replaceWith is the variant that tolerates null results
🏷️ Related Tags
💡 Related Cases
📚 Related Tutorials
❓ FAQ
QWhat is the difference between $replaceRoot and $project?
A$project selects or computes fields from the original; $replaceRoot swaps in an entirely new document.
QWhat if the newRoot field does not exist?
AIt errors. Guard with $ifNull or use the $replaceWith variant.
QHow do I lift one nesting level instead of replacing everything?
AFor partial lifting use dotted-path expressions in $project; $replaceRoot replaces the whole root.