0
0
MongoDBquery~5 mins

$unwind for flattening arrays in MongoDB - Cheat Sheet & Quick Revision

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

The $unwind stage takes an array field from each document and creates a separate document for each element in that array. This 'flattens' the array so you can work with each element individually.

Click to reveal answer
intermediate
How does $unwind affect documents that have an empty array or missing array field?

By default, $unwind removes documents where the array is empty or the field is missing. You can change this behavior with the preserveNullAndEmptyArrays option to keep those documents.

Click to reveal answer
beginner
Example: Given a document { name: 'Alice', hobbies: ['reading', 'swimming'] }, what will $unwind: '$hobbies' produce?

It will produce two documents:<br>{ name: 'Alice', hobbies: 'reading' }<br>{ name: 'Alice', hobbies: 'swimming' }

Click to reveal answer
intermediate
What option can you use with $unwind to keep documents that have empty or missing arrays?

You can use { preserveNullAndEmptyArrays: true } inside $unwind to keep documents even if the array is empty or missing.

Click to reveal answer
beginner
Why is $unwind useful when working with arrays in MongoDB?

It helps to break down arrays into individual elements so you can filter, group, or sort based on each element separately, making data analysis easier.

Click to reveal answer
What does the $unwind stage do in MongoDB?
AJoins two collections together
BSorts documents by array length
CDeletes documents with empty arrays
DSplits array elements into separate documents
If a document has an empty array field, what happens by default when using $unwind on that field?
AThe document is removed from the output
BThe document is kept unchanged
CThe array is filled with nulls
DAn error is thrown
Which option allows $unwind to keep documents with empty or missing arrays?
AkeepEmptyArrays: true
BincludeEmpty: true
CpreserveNullAndEmptyArrays: true
DallowEmpty: true
Given { name: 'Bob', tags: ['fun', 'smart'] }, what does $unwind: '$tags' produce?
AOne document with tags as an array
BTwo documents, each with one tag
CNo documents
DOne document with tags as a string 'fun, smart'
Why would you use $unwind in an aggregation pipeline?
ATo flatten arrays for easier filtering and grouping
BTo delete array fields
CTo combine multiple arrays into one
DTo rename fields
Explain how the $unwind stage works in MongoDB and why it is useful.
Think about how arrays become easier to work with when broken down.
You got /4 concepts.
    Describe what happens to documents with empty or missing arrays when using $unwind and how to change this behavior.
    Consider the default behavior and the option to keep those documents.
    You got /3 concepts.