0
0
MongoDBquery~5 mins

$replaceRoot for restructuring in MongoDB - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the $replaceRoot stage do in a MongoDB aggregation pipeline?

$replaceRoot replaces the current document with a specified embedded document. It helps restructure documents by promoting a nested document to the top level.

Click to reveal answer
beginner
How do you specify the new root document in $replaceRoot?

You use the newRoot field inside $replaceRoot to specify the embedded document that will become the new root.

Click to reveal answer
beginner
Example: If a document is { _id: 1, info: { name: 'Alice', age: 30 } }, what will { $replaceRoot: { newRoot: '$info' } } produce?

The output document will be { name: 'Alice', age: 30 }. The info subdocument becomes the whole document.

Click to reveal answer
intermediate
Can $replaceRoot be used to flatten nested documents?

Yes, by replacing the root with a nested document, you effectively flatten the structure by removing the outer layers.

Click to reveal answer
intermediate
What happens if the newRoot field in $replaceRoot does not exist in the document?

The aggregation will return null for that document, effectively removing it from the output if followed by a $match or similar stage.

Click to reveal answer
What is the main purpose of $replaceRoot in MongoDB?
ATo delete documents from the collection
BTo replace the current document with a nested document
CTo add new fields to the document
DTo sort documents by a field
Which field do you use inside $replaceRoot to specify the new root document?
ArootDoc
Bdocument
CreplaceWith
DnewRoot
Given { _id: 2, details: { city: 'NY', zip: 10001 } }, what does { $replaceRoot: { newRoot: '$details' } } output?
A{ city: 'NY', zip: 10001 }
B{ _id: 2 }
C{ _id: 2, details: { city: 'NY', zip: 10001 } }
Dnull
If the specified newRoot path does not exist in a document, what is the result?
AThe original document is kept
BAn error is thrown
CThe document becomes <code>null</code>
DThe document is duplicated
Can $replaceRoot be used to promote a nested document to the top level?
AYes
BNo
COnly with <code>$project</code>
DOnly with <code>$group</code>
Explain how $replaceRoot works in MongoDB aggregation and give a simple example.
Think about changing the shape of documents by picking a nested part as the whole document.
You got /3 concepts.
    What happens if the path specified in newRoot does not exist in a document during $replaceRoot?
    Consider how missing data affects the output document.
    You got /3 concepts.