0
0
MongoDBquery~5 mins

$size operator for array length in MongoDB - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the $size operator do in MongoDB?
The $size operator returns the number of elements in an array field in a document.
Click to reveal answer
beginner
How do you use $size in a MongoDB query to find documents where an array has exactly 3 elements?
Use { arrayField: { $size: 3 } } in the query to find documents where arrayField has exactly 3 elements.
Click to reveal answer
intermediate
Can $size be used to find arrays with length greater than or less than a number?
No, $size only matches arrays with an exact length. For greater or less than, use $expr with $gt or $lt and $size inside.
Click to reveal answer
beginner
Example: Find documents where the tags array has 2 elements.
Query: { tags: { $size: 2 } } will return documents where the tags array length is exactly 2.
Click to reveal answer
beginner
Why is $size useful in real life?
It helps find documents with arrays of a specific length, like users with exactly 3 phone numbers or orders with 5 items.
Click to reveal answer
What does { items: { $size: 4 } } find in MongoDB?
ADocuments where 'items' array has less than 4 elements
BDocuments where 'items' array has more than 4 elements
CDocuments where 'items' array has exactly 4 elements
DDocuments where 'items' array contains the number 4
Can $size be used to find arrays with length greater than 5?
ANo, <code>$size</code> only matches exact lengths
BYes, directly with <code>$size</code>
CYes, but only in aggregation pipelines
DNo, arrays cannot be filtered by length
Which query finds documents with an array 'scores' of length 3?
A{ scores: { $size: 3 } }
B{ scores: { $gt: 3 } }
C{ scores: { $length: 3 } }
D{ scores: { $count: 3 } }
What type of MongoDB field does $size work on?
AString fields
BArray fields
CNumber fields
DDate fields
If a document has tags: ['a', 'b', 'c'], which query matches it?
A{ tags: { $size: 1 } }
B{ tags: { $size: 2 } }
C{ tags: { $size: 4 } }
D{ tags: { $size: 3 } }
Explain how the $size operator works in MongoDB and give an example query.
Think about how to find documents with arrays of a certain length.
You got /3 concepts.
    Describe a situation where $size is useful and how you would write a query for it.
    Consider arrays like tags, phone numbers, or items in orders.
    You got /3 concepts.