0
0
MongoDBquery~30 mins

$replaceRoot for restructuring in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
$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
Need a 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
Need a 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
Need a 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
Need a hint?

Use db.orders.aggregate(pipeline) to run the pipeline and assign it to restructuredOrders.