Bird
Raised Fist0
MongoDBquery~5 mins

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

Choose your learning style10 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.

      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

      1. Step 1: Understand the purpose of $replaceRoot

        $replaceRoot replaces the whole document with a specified nested document inside it.
      2. Step 2: Compare with other stages

        Filtering, sorting, and grouping are done by $match, $sort, and $group respectively, not $replaceRoot.
      3. Final Answer:

        It replaces the entire document with the specified embedded document. -> Option C
      4. 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

      1. Step 1: Recall correct $replaceRoot syntax

        The correct syntax requires newRoot with a string path starting with "$" to specify the field.
      2. 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.
      3. Final Answer:

        { $replaceRoot: { newRoot: "$details" } } -> Option A
      4. Quick Check:

        Use newRoot: "$field" syntax [OK]
      Hint: Use newRoot: "$fieldName" exactly [OK]
      Common Mistakes:
      • Omitting quotes around field path
      • Using wrong key like 'root' instead of 'newRoot'
      • Combining stages incorrectly
      3. Given the collection documents:
      { "name": "Alice", "info": { "age": 30, "city": "NY" } }

      What will be the output of this aggregation?
      [{ $replaceRoot: { newRoot: "$info" } }]
      medium
      A. [{ "name": "Alice", "info": { "age": 30, "city": "NY" } }]
      B. [{ "age": 30, "city": "NY" }]
      C. [{ "info": { "age": 30, "city": "NY" } }]
      D. [{ "age": 30 }]

      Solution

      1. Step 1: Understand $replaceRoot effect

        The stage replaces the whole document with the content of the info field.
      2. Step 2: Apply to given document

        Original document has info as { "age": 30, "city": "NY" }, so output document is exactly that object.
      3. Final Answer:

        [{ "age": 30, "city": "NY" }] -> Option B
      4. Quick Check:

        Root replaced by info field content [OK]
      Hint: Output matches the nested field content exactly [OK]
      Common Mistakes:
      • Expecting original fields to remain
      • Confusing nested field with root
      • Selecting wrong output format
      4. You wrote this aggregation but it throws an error:
      [{ $replaceRoot: { newRoot: info } }]

      What is the error and how to fix it?
      medium
      A. Missing quotes around field path; fix with newRoot: "$info".
      B. Wrong operator; use $setRoot instead of $replaceRoot.
      C. Field info does not exist; add it first.
      D. Aggregation pipeline must be an object, not an array.

      Solution

      1. Step 1: Identify syntax error in newRoot value

        The field path must be a string starting with "$" to indicate a field reference.
      2. Step 2: Correct the syntax

        Change newRoot: info to newRoot: "$info" to fix the error.
      3. Final Answer:

        Missing quotes around field path; fix with newRoot: "$info". -> Option A
      4. Quick Check:

        Field paths need quotes and $ prefix [OK]
      Hint: Always quote field paths with $ prefix [OK]
      Common Mistakes:
      • Omitting quotes around field names
      • Confusing $replaceRoot with $setRoot
      • Misunderstanding pipeline array structure
      5. You have documents:
      { "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?
      hard
      A. [{ $replaceRoot: { newRoot: "$score" } }]
      B. [{ $replaceRoot: { newRoot: "$user" } }, { $addFields: { score: "$score" } }]
      C. [{ $project: { user: 1, score: 1 } }]
      D. [{ $replaceRoot: { newRoot: { $mergeObjects: ["$user", { score: "$score" }] } } }]

      Solution

      1. Step 1: Understand the goal

        We want to flatten user fields to root and keep score alongside.
      2. Step 2: Use $mergeObjects inside $replaceRoot

        $mergeObjects combines user object and { score: "$score" } into one root document.
      3. 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, but score is lost after first stage. [{ $project: { user: 1, score: 1 } }] only projects fields, not restructuring. [{ $replaceRoot: { newRoot: "$score" } }] replaces root with score only, losing user.
      4. Final Answer:

        [{ $replaceRoot: { newRoot: { $mergeObjects: ["$user", { score: "$score" }] } } }] -> Option D
      5. Quick Check:

        Use $mergeObjects to combine fields [OK]
      Hint: Combine objects with $mergeObjects inside $replaceRoot [OK]
      Common Mistakes:
      • Replacing root with only one field losing others
      • Trying to add fields after $replaceRoot without preserving data
      • Using $project instead of restructuring
      Recommended

      Ready to prove it?

      Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

      10 questions~5 mineasy hard