0
0
MongoDBquery~20 mins

$size operator for array length in MongoDB - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Array Length Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2: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 } })
Adb.students.find({ $size: { courses: 3 } })
Bdb.students.find({ courses: { $size: 3 } })
Cdb.students.find({ courses: { $length: 3 } })
Ddb.students.find({ courses: { $count: 3 } })
Attempts:
2 left
💡 Hint
Use the $size operator inside the query to match array length.
🧠 Conceptual
intermediate
1:30remaining
Understanding $size operator behavior
What does the $size operator do in a MongoDB query?
AFilters documents where the array contains at least the given number of elements.
BCounts the total number of documents in the collection.
CReturns the length of a string field in the document.
DMatches documents where the specified array field has exactly the given number of elements.
Attempts:
2 left
💡 Hint
Think about how $size relates to arrays.
📝 Syntax
advanced
2: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: ??? } } ])
A{ $size: "$tags" }
B{ $length: "$tags" }
C{ $count: "$tags" }
D{ $size: tags }
Attempts:
2 left
💡 Hint
Use $size with the array field as a string path.
🔧 Debug
advanced
2:00remaining
Why does this query fail?
Consider the query: db.orders.find({ items: { $size: "3" } }). Why does this query not return any documents?
ABecause the collection 'orders' does not exist.
BBecause $size cannot be used inside find queries.
CBecause $size expects a number, not a string, so "3" is invalid.
DBecause the field name 'items' is misspelled.
Attempts:
2 left
💡 Hint
Check the data type used with $size.
optimization
expert
3: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?
ACreate an index on the <code>comments</code> field and use <code>{ comments: { $size: 5 } }</code> in the query.
BUse <code>{ comments: { $size: 5 } }</code> without any index.
CUse <code>{ comments: { $exists: true } }</code> and filter array length in application code.
DUse <code>{ $expr: { $eq: [ { $size: "$comments" }, 5 ] } }</code> without any index.
Attempts:
2 left
💡 Hint
Indexes help speed up queries on large data.