Challenge - 5 Problems
MongoDB $replaceRoot Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
What is the output of this $replaceRoot aggregation?
Given the collection documents:
What will be the output of this aggregation?
{ "_id": 1, "user": { "name": "Alice", "age": 30 }, "score": 85 }What will be the output of this aggregation?
[{ $replaceRoot: { newRoot: "$user" } }]MongoDB
[{ $replaceRoot: { newRoot: "$user" } }]Attempts:
2 left
💡 Hint
Think about what $replaceRoot does with the specified newRoot field.
✗ Incorrect
$replaceRoot replaces the entire document with the specified field's content. Here, it replaces the root with the 'user' subdocument.
❓ query_result
intermediate2:00remaining
What does this $replaceRoot pipeline produce?
Given documents:
Run this pipeline:
{ "_id": 2, "order": { "id": 101, "items": 3 }, "status": "shipped" }Run this pipeline:
[{ $replaceRoot: { newRoot: { $mergeObjects: ["$order", { "status": "$status" }] } } }]MongoDB
[{ $replaceRoot: { newRoot: { $mergeObjects: ["$order", { "status": "$status" }] } } }]Attempts:
2 left
💡 Hint
Look at how $mergeObjects combines fields from two documents.
✗ Incorrect
$mergeObjects merges the 'order' subdocument with a new document containing 'status'. $replaceRoot then sets this merged document as the root.
📝 Syntax
advanced2:00remaining
Which $replaceRoot usage is syntactically correct?
Choose the option with correct syntax for $replaceRoot stage in MongoDB aggregation.
Attempts:
2 left
💡 Hint
Check the exact field name and value type required by $replaceRoot.
✗ Incorrect
$replaceRoot requires an object with a 'newRoot' field whose value is an expression (usually a string path).
❓ optimization
advanced2:00remaining
How to optimize restructuring with $replaceRoot and $project?
You want to restructure documents by replacing the root with the 'profile' field but also keep the original '_id'. Which pipeline is best?
Attempts:
2 left
💡 Hint
Consider how to keep _id while replacing root in one step.
✗ Incorrect
Option B merges 'profile' with an object containing '_id', then replaces root with the merged object, preserving _id efficiently.
🧠 Conceptual
expert2:00remaining
What error occurs if $replaceRoot newRoot field is missing?
Consider this aggregation stage:
What error will MongoDB raise when running this?
{ $replaceRoot: { } }What error will MongoDB raise when running this?
Attempts:
2 left
💡 Hint
Think about required fields for $replaceRoot stage.
✗ Incorrect
The $replaceRoot stage requires the 'newRoot' field. Omitting it causes a MongoError indicating the missing required field.