$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.

CategoryCore Stages
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $replaceRoot: { newRoot: <document expression> } }

⚙️ Parameters

newRootExpression 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

📚 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏