$replaceRoot for restructuring in MongoDB - Time & Space Complexity
We want to understand how the time it takes to run a MongoDB query using $replaceRoot changes as the amount of data grows.
Specifically, we ask: How does the work grow when we restructure many documents?
Analyze the time complexity of the following code snippet.
db.orders.aggregate([
{ $match: { status: "A" } },
{ $replaceRoot: { newRoot: "$details" } }
])
This query filters orders with status "A" and then replaces each document with its "details" field.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Processing each matching document once to replace its root.
- How many times: Once per matching document in the collection.
As the number of matching documents grows, the query processes each one individually.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 document replacements |
| 100 | 100 document replacements |
| 1000 | 1000 document replacements |
Pattern observation: The work grows directly with the number of documents processed.
Time Complexity: O(n)
This means the time to run the query grows in a straight line with the number of documents it processes.
[X] Wrong: "Using $replaceRoot will make the query run faster because it changes the document structure."
[OK] Correct: Changing the document shape with $replaceRoot still requires processing each document, so it does not reduce the number of documents or the work done.
Understanding how MongoDB aggregation stages like $replaceRoot scale helps you explain query performance clearly and confidently in real-world situations.
What if we replaced $replaceRoot with $project to reshape documents? How would the time complexity change?
Practice
$replaceRoot stage do in a MongoDB aggregation pipeline?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]
$replaceRoot swaps the whole document root [OK]- Confusing
$replaceRootwith filtering or sorting stages - Thinking it only modifies part of the document
- Assuming it adds fields instead of replacing
$replaceRoot to replace the root with the details field?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]
newRoot: "$fieldName" exactly [OK]- Omitting quotes around field path
- Using wrong key like 'root' instead of 'newRoot'
- Combining stages incorrectly
{ "name": "Alice", "info": { "age": 30, "city": "NY" } }What will be the output of this aggregation?
[{ $replaceRoot: { newRoot: "$info" } }]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]
- Expecting original fields to remain
- Confusing nested field with root
- Selecting wrong output format
[{ $replaceRoot: { newRoot: info } }]What is the error and how to fix it?
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]
- Omitting quotes around field names
- Confusing
$replaceRootwith$setRoot - Misunderstanding pipeline array structure
{ "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?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]
$mergeObjects inside $replaceRoot [OK]- Replacing root with only one field losing others
- Trying to add fields after
$replaceRootwithout preserving data - Using
$projectinstead of restructuring
Ready to prove it?
Pass the test and this pattern moves unknown
