$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.
$replaceRoot for restructuring in MongoDB
Introduction
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
address object.MongoDB
{ $replaceRoot: { newRoot: "$address" } }contact object with a new field status and makes it the root.MongoDB
{ $replaceRoot: { newRoot: { $mergeObjects: ["$contact", { status: "active" }] } } }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" } }
])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.
Practice
1. What does the
$replaceRoot stage do in a MongoDB aggregation pipeline?easy
Solution
Step 1: Understand the purpose of
$replaceRoot$replaceRootreplaces the whole document with a specified nested document inside it.Step 2: Compare with other stages
Filtering, sorting, and grouping are done by$match,$sort, and$grouprespectively, not$replaceRoot.Final Answer:
It replaces the entire document with the specified embedded document. -> Option CQuick Check:
$replaceRootchanges document root [OK]
Hint: Remember:
$replaceRoot swaps the whole document root [OK]Common Mistakes:
- Confusing
$replaceRootwith filtering or sorting stages - Thinking it only modifies part of the document
- Assuming it adds fields instead of replacing
2. Which of the following is the correct syntax to use
$replaceRoot to replace the root with the details field?easy
Solution
Step 1: Recall correct
The correct syntax requires$replaceRootsyntaxnewRootwith a string path starting with "$" to specify the field.Step 2: Analyze options
{ $replaceRoot: { newRoot: "$details" } } usesnewRoot: "$details"which is correct. { $replaceRoot: { root: "$details" } } uses wrong keyroot. { $replaceRoot: { newRoot: details } } misses quotes around field path. { $replaceRoot: { newRoot: "$details" }, $match: {} } adds an unrelated$matchinside the same stage, which is invalid.Final Answer:
{ $replaceRoot: { newRoot: "$details" } } -> Option AQuick Check:
UsenewRoot: "$field"syntax [OK]
Hint: Use
newRoot: "$fieldName" exactly [OK]Common Mistakes:
- Omitting quotes around field path
- Using wrong key like 'root' instead of 'newRoot'
- Combining stages incorrectly
3. Given the collection documents:
What will be the output of this aggregation?
{ "name": "Alice", "info": { "age": 30, "city": "NY" } }What will be the output of this aggregation?
[{ $replaceRoot: { newRoot: "$info" } }]medium
Solution
Step 1: Understand
The stage replaces the whole document with the content of the$replaceRooteffectinfofield.Step 2: Apply to given document
Original document hasinfoas { "age": 30, "city": "NY" }, so output document is exactly that object.Final Answer:
[{ "age": 30, "city": "NY" }] -> Option BQuick Check:
Root replaced byinfofield content [OK]
Hint: Output matches the nested field content exactly [OK]
Common Mistakes:
- Expecting original fields to remain
- Confusing nested field with root
- Selecting wrong output format
4. You wrote this aggregation but it throws an error:
What is the error and how to fix it?
[{ $replaceRoot: { newRoot: info } }]What is the error and how to fix it?
medium
Solution
Step 1: Identify syntax error in
The field path must be a string starting with "$" to indicate a field reference.newRootvalueStep 2: Correct the syntax
ChangenewRoot: infotonewRoot: "$info"to fix the error.Final Answer:
Missing quotes around field path; fix withnewRoot: "$info". -> Option AQuick Check:
Field paths need quotes and $ prefix [OK]
Hint: Always quote field paths with $ prefix [OK]
Common Mistakes:
- Omitting quotes around field names
- Confusing
$replaceRootwith$setRoot - Misunderstanding pipeline array structure
5. You have documents:
How do you write an aggregation pipeline using
{ "user": { "id": 1, "name": "Bob" }, "score": 50 }How do you write an aggregation pipeline using
$replaceRoot to make the output documents only contain the user fields plus the score field at the root level?hard
Solution
Step 1: Understand the goal
We want to flattenuserfields to root and keepscorealongside.Step 2: Use
$mergeObjectsinside$replaceRoot$mergeObjectscombinesuserobject and{ score: "$score" }into one root document.Step 3: Check options
[{ $replaceRoot: { newRoot: { $mergeObjects: ["$user", { score: "$score" }] } } }] correctly merges and replaces root. [{ $replaceRoot: { newRoot: "$user" } }, { $addFields: { score: "$score" } }] tries to add fields after replacing root, butscoreis lost after first stage. [{ $project: { user: 1, score: 1 } }] only projects fields, not restructuring. [{ $replaceRoot: { newRoot: "$score" } }] replaces root withscoreonly, losinguser.Final Answer:
[{ $replaceRoot: { newRoot: { $mergeObjects: ["$user", { score: "$score" }] } } }] -> Option DQuick Check:
Use$mergeObjectsto combine fields [OK]
Hint: Combine objects with
$mergeObjects inside $replaceRoot [OK]Common Mistakes:
- Replacing root with only one field losing others
- Trying to add fields after
$replaceRootwithout preserving data - Using
$projectinstead of restructuring
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
