0
0
MongoDBquery~5 mins

$replaceRoot for restructuring in MongoDB

Choose your learning style9 modes available
Introduction

$replaceRoot helps you change the shape of your data by replacing the whole document with a part of it. This makes it easier to work with nested information.

You want to flatten nested objects inside your documents to work with them directly.
You need to simplify the structure of your data for reporting or analysis.
You want to remove unnecessary outer layers of your documents to focus on important details.
You are preparing data for export and want a cleaner format.
You want to merge fields from a nested document into the top-level document.
Syntax
MongoDB
{ $replaceRoot: { newRoot: <document> } }

newRoot is the part of the document you want to keep as the new root.

You can use any field or expression that results in a document.

Examples
This replaces the whole document with the nested address object.
MongoDB
{ $replaceRoot: { newRoot: "$address" } }
This merges the contact object with a new field status and makes it the root.
MongoDB
{ $replaceRoot: { newRoot: { $mergeObjects: ["$contact", { status: "active" }] } } }
This replaces the document with the nested details inside profile.
MongoDB
{ $replaceRoot: { newRoot: "$profile.details" } }
Sample Program

This query takes the contact field from each users document and makes it the whole document in the output.

MongoDB
db.users.aggregate([
  { $replaceRoot: { newRoot: "$contact" } }
])
OutputSuccess
Important Notes

If the newRoot field does not exist, the document will be replaced with null.

You can combine $replaceRoot with other stages like $match or $project for more control.

Summary

$replaceRoot changes the whole document to a nested part you choose.

It helps simplify or flatten data structures.

Use it when you want to focus on a specific part of your documents.