$replaceRoot for restructuring documents in MongoDB
📖 Scenario: You work at a company that stores customer orders in a MongoDB collection. Each order document contains a nested customer object with details about the customer. You want to restructure the documents so that the customer details become the top-level fields, replacing the original root document.
🎯 Goal: Build a MongoDB aggregation pipeline that uses $replaceRoot to restructure each order document by replacing the root with the nested customer object.
📋 What You'll Learn
Create a collection named orders with sample documents containing a nested customer field.
Define a variable for the aggregation pipeline.
Use the $replaceRoot stage to replace the root document with the customer object.
Complete the aggregation pipeline to output the restructured documents.
💡 Why This Matters
🌍 Real World
Restructuring nested documents is common when you want to simplify data views or prepare data for reporting and analysis.
💼 Career
Understanding how to use MongoDB aggregation stages like <code>$replaceRoot</code> is valuable for backend developers and data engineers working with NoSQL databases.
Progress0 / 4 steps
1
Create the orders collection with sample documents
Create a variable called orders and assign it an array with two documents. Each document should have an orderId field and a nested customer object. The first document's orderId is 101 and customer has name as "Alice" and city as "New York". The second document's orderId is 102 and customer has name as "Bob" and city as "Los Angeles".
MongoDB
Hint
Use a list of dictionaries. Each dictionary has orderId and customer keys. The customer key holds another dictionary with name and city.
2
Define the aggregation pipeline variable
Create a variable called pipeline and assign it an empty array. This will hold the stages of the MongoDB aggregation pipeline.
MongoDB
Hint
Just create an empty list named pipeline to start building the aggregation stages.
3
Add the $replaceRoot stage to the pipeline
Add a dictionary to the pipeline list. This dictionary should have the key $replaceRoot with a value that is another dictionary containing newRoot set to "$customer". This stage will replace the root document with the nested customer object.
MongoDB
Hint
Use {"$replaceRoot": {"newRoot": "$customer"}} as a stage inside the pipeline list.
4
Complete the aggregation pipeline to restructure documents
Add a variable called restructuredOrders and assign it the result of calling db.orders.aggregate(pipeline). This runs the aggregation pipeline on the orders collection to produce documents where the root is replaced by the customer object.
MongoDB
Hint
Use db.orders.aggregate(pipeline) to run the pipeline and assign it to restructuredOrders.
Practice
(1/5)
1. What does the $replaceRoot stage do in a MongoDB aggregation pipeline?
easy
A. It groups documents by a specified key.
B. It filters documents based on a condition.
C. It replaces the entire document with the specified embedded document.
D. It sorts documents by a specified field.
Solution
Step 1: Understand the purpose of $replaceRoot
$replaceRoot replaces 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 $group respectively, not $replaceRoot.
Final Answer:
It replaces the entire document with the specified embedded document. -> Option C
Quick Check:
$replaceRoot changes document root [OK]
Hint: Remember: $replaceRoot swaps the whole document root [OK]
Common Mistakes:
Confusing $replaceRoot with 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
A. { $replaceRoot: { newRoot: "$details" } }
B. { $replaceRoot: { root: "$details" } }
C. { $replaceRoot: { newRoot: details } }
D. { $replaceRoot: { newRoot: "$details" }, $match: {} }
Solution
Step 1: Recall correct $replaceRoot syntax
The correct syntax requires newRoot with a string path starting with "$" to specify the field.
Step 2: Analyze options
{ $replaceRoot: { newRoot: "$details" } } uses newRoot: "$details" which is correct. { $replaceRoot: { root: "$details" } } uses wrong key root. { $replaceRoot: { newRoot: details } } misses quotes around field path. { $replaceRoot: { newRoot: "$details" }, $match: {} } adds an unrelated $match inside the same stage, which is invalid.
Final Answer:
{ $replaceRoot: { newRoot: "$details" } } -> Option A
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?