0
0
MongoDBquery~20 mins

$unwind for flattening arrays in MongoDB - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
MongoDB $unwind Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
What is the output of this $unwind operation?
Given the collection documents:
{ _id: 1, fruits: ["apple", "banana"] }
What will be the result of this aggregation?
[{ $unwind: "$fruits" }]
A[{ _id: 1, fruits: "apple" }, { _id: 1, fruits: "banana" }]
B[{ _id: 1, fruits: ["apple"] }, { _id: 1, fruits: ["banana"] }]
C[{ _id: 1, fruits: "apple" }]
D[{ _id: 1, fruits: ["apple", "banana"] }]
Attempts:
2 left
💡 Hint
Think about how $unwind breaks down arrays into separate documents.
📝 Syntax
intermediate
1:30remaining
Which $unwind syntax is correct to flatten the 'tags' array?
Choose the correct $unwind stage to flatten the 'tags' array in documents.
A{ $unwind: ["$tags"] }
B{ $unwind: "$tags" }
C{ $unwind: tags }
D{ $unwind: { path: "tags" } }
Attempts:
2 left
💡 Hint
Remember $unwind expects a string path with $ prefix or an object with path field.
query_result
advanced
2:30remaining
What is the output when using $unwind with preserveNullAndEmptyArrays?
Given documents:
{ _id: 1, items: ["pen", "pencil"] }, { _id: 2 }
What is the result of:
[{ $unwind: { path: "$items", preserveNullAndEmptyArrays: true } }]
A[{ _id: 1, items: ["pen", "pencil"] }, { _id: 2 }]
B[{ _id: 1, items: "pen" }, { _id: 1, items: "pencil" }]
C[{ _id: 1, items: "pen" }, { _id: 1, items: "pencil" }, { _id: 2, items: null }]
D[{ _id: 1, items: "pen" }, { _id: 2, items: null }]
Attempts:
2 left
💡 Hint
PreserveNullAndEmptyArrays keeps documents without the array or with empty arrays.
optimization
advanced
2:00remaining
How to optimize $unwind when array field might be missing or empty?
You want to unwind the 'comments' array but keep documents without comments or with empty arrays. Which $unwind stage is best?
A{ $unwind: { path: "$comments" } }
B{ $unwind: "$comments" }
C{ $unwind: { path: "$comments", preserveNullAndEmptyArrays: false } }
D{ $unwind: { path: "$comments", preserveNullAndEmptyArrays: true } }
Attempts:
2 left
💡 Hint
Consider documents that may not have the array field or have it empty.
🧠 Conceptual
expert
2:30remaining
What happens if you $unwind a non-array field?
If a document has a field 'score' with a single integer value (not an array), what happens when you apply:
[{ $unwind: "$score" }]
AThe document is removed from the output because 'score' is not an array.
BThe aggregation throws an error because $unwind expects an array field.
CThe document is duplicated once for the single value of 'score'.
DThe document is passed through unchanged because 'score' is not an array.
Attempts:
2 left
💡 Hint
Think about how $unwind treats fields that are not arrays.