Bird
Raised Fist0
MongoDBquery~20 mins

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

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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.

Practice

(1/5)
1. What does the $size operator do in MongoDB?
easy
A. Counts the number of elements in an array
B. Calculates the sum of numbers in an array
C. Finds the largest number in an array
D. Sorts the elements of an array

Solution

  1. Step 1: Understand the purpose of $size

    The $size operator is used to count how many elements are inside an array field in a MongoDB document.
  2. Step 2: Compare with other options

    Other options describe different operations like sum, max, or sort, which are not what $size does.
  3. Final Answer:

    Counts the number of elements in an array -> Option A
  4. Quick Check:

    $size = count array elements [OK]
Hint: Remember: $size counts array items, not values [OK]
Common Mistakes:
  • Confusing $size with sum or max functions
  • Thinking $size sorts arrays
  • Using $size on non-array fields
2. Which of the following is the correct syntax to use $size in a MongoDB aggregation pipeline to add a field itemCount that counts elements in the items array?
easy
A. { $addFields: { itemCount: { $length: "$items" } } }
B. { $match: { itemCount: { $size: "$items" } } }
C. { $project: { itemCount: { $size: "items" } } }
D. { $addFields: { itemCount: { $size: "$items" } } }

Solution

  1. Step 1: Identify correct operator usage in aggregation

    The $size operator is used inside an expression to count array elements. It must be inside a stage like $addFields or $project with the array field referenced as "$items".
  2. Step 2: Check syntax correctness

    { $addFields: { itemCount: { $length: "$items" } } } uses a non-existent $length. { $project: { itemCount: { $size: "items" } } } misses the $ before items. { $match: { itemCount: { $size: "$items" } } } misuses $match with $size.
  3. Final Answer:

    { $addFields: { itemCount: { $size: "$items" } } } -> Option D
  4. Quick Check:

    Use $size inside $addFields with "$arrayField" [OK]
Hint: Use "$arrayField" inside $size in $addFields or $project [OK]
Common Mistakes:
  • Using $length instead of $size
  • Forgetting the $ before array field name
  • Using $size inside $match incorrectly
3. Given the collection documents:
{ "name": "Alice", "tags": ["red", "blue"] }
{ "name": "Bob", "tags": ["green"] }
{ "name": "Carol", "tags": [] }

What will be the result of this aggregation pipeline?
[{ $project: { name: 1, tagCount: { $size: "$tags" } } }]
medium
A. [{ "name": "Alice", "tagCount": 2 }, { "name": "Bob", "tagCount": 1 }, { "name": "Carol", "tagCount": 0 }]
B. [{ "name": "Alice", "tagCount": 3 }, { "name": "Bob", "tagCount": 1 }, { "name": "Carol", "tagCount": 1 }]
C. [{ "name": "Alice", "tagCount": 2 }, { "name": "Bob", "tagCount": 0 }, { "name": "Carol", "tagCount": 0 }]
D. SyntaxError

Solution

  1. Step 1: Understand $size counts array elements

    For each document, $size counts how many items are in the tags array: Alice has 2, Bob has 1, Carol has 0.
  2. Step 2: Apply $project to include name and tagCount

    The pipeline projects the name and adds tagCount with the counted size.
  3. Final Answer:

    [{ "name": "Alice", "tagCount": 2 }, { "name": "Bob", "tagCount": 1 }, { "name": "Carol", "tagCount": 0 }] -> Option A
  4. Quick Check:

    Count array lengths with $size = correct counts [OK]
Hint: Count array length per document with $size in $project [OK]
Common Mistakes:
  • Assuming empty arrays count as 1
  • Mixing up counts for different documents
  • Expecting syntax error for correct query
4. You wrote this aggregation stage to filter documents with exactly 3 tags:
{ $match: { tags: { $size: 3 } } }

But it returns an error. What is the problem?
medium
A. The array field name is missing the $ sign
B. The $match stage requires $expr to use $size
C. The number 3 should be in quotes as "3"
D. $size cannot be used inside $match like this

Solution

  1. Step 1: Understand $size usage in $match

    Directly using $size inside $match like this is invalid because $size is an aggregation expression, not a query operator.
  2. Step 2: Use $expr to evaluate aggregation expressions in $match

    To filter by array length, you must use $expr with $size, like: { $match: { $expr: { $eq: [ { $size: "$tags" }, 3 ] } } }.
  3. Final Answer:

    The $match stage requires $expr to use $size -> Option B
  4. Quick Check:

    Use $expr for aggregation expressions in $match [OK]
Hint: Use $expr to apply $size inside $match [OK]
Common Mistakes:
  • Trying to use $size directly in $match
  • Forgetting $expr wrapper
  • Using quotes around numbers incorrectly
5. You want to find documents where the comments array has more than 2 elements. Which aggregation pipeline stage correctly filters these documents?
hard
A. { $match: { $size: { $gt: [ "$comments", 2 ] } } }
B. { $match: { comments: { $size: { $gt: 2 } } } }
C. { $match: { $expr: { $gt: [ { $size: "$comments" }, 2 ] } } }
D. { $match: { $expr: { $size: { $gt: [ "$comments", 2 ] } } } }

Solution

  1. Step 1: Use $expr to evaluate expressions in $match

    To compare array length, use $expr to allow aggregation expressions inside $match.
  2. Step 2: Use $gt with $size to check array length greater than 2

    The correct syntax is { $gt: [ { $size: "$comments" }, 2 ] } inside $expr.
  3. Step 3: Eliminate incorrect options

    The incorrect options either lack $expr, misuse $size placement, or have wrong syntax for $gt.
  4. Final Answer:

    { $match: { $expr: { $gt: [ { $size: "$comments" }, 2 ] } } } -> Option C
  5. Quick Check:

    Filter by array length with $expr and $gt [OK]
Hint: Use $expr with $gt and $size to filter by array length [OK]
Common Mistakes:
  • Using $size as a query operator inside $match
  • Wrong order or structure of $gt and $size
  • Missing $expr wrapper