Challenge - 5 Problems
Array Length Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Find documents with array length exactly 3
Given a collection students where each document has a field
courses which is an array of course names, which query returns all students enrolled in exactly 3 courses?MongoDB
db.students.find({ courses: { $size: 3 } })Attempts:
2 left
💡 Hint
Use the $size operator inside the query to match array length.
✗ Incorrect
The $size operator matches arrays with the exact specified length. Only option B uses $size correctly.
🧠 Conceptual
intermediate1:30remaining
Understanding $size operator behavior
What does the $size operator do in a MongoDB query?
Attempts:
2 left
💡 Hint
Think about how $size relates to arrays.
✗ Incorrect
$size matches documents where the array field length equals the specified number exactly.
📝 Syntax
advanced2:30remaining
Identify the correct aggregation pipeline stage using $size
Which aggregation pipeline stage correctly adds a new field
numTags that contains the length of the tags array in each document?MongoDB
db.posts.aggregate([ { $addFields: { numTags: ??? } } ])Attempts:
2 left
💡 Hint
Use $size with the array field as a string path.
✗ Incorrect
In aggregation, $size takes a field path as a string to compute array length. Only option A is correct syntax.
🔧 Debug
advanced2:00remaining
Why does this query fail?
Consider the query:
db.orders.find({ items: { $size: "3" } }). Why does this query not return any documents?Attempts:
2 left
💡 Hint
Check the data type used with $size.
✗ Incorrect
$size requires a numeric value to specify array length. Using a string causes no matches.
❓ optimization
expert3:00remaining
Optimizing queries with $size on large collections
You have a large collection with millions of documents. You want to find documents where the
comments array has exactly 5 elements. Which approach is most efficient?Attempts:
2 left
💡 Hint
Indexes help speed up queries on large data.
✗ Incorrect
MongoDB supports multikey indexes on array fields. Indexing
comments allows efficient $size queries.