Hint: Query returns docs where array contains value [OK]
Common Mistakes:
Expecting only one document
Thinking query returns empty if multiple matches
Confusing syntax error with valid query
4. Consider this incorrect MongoDB query to find documents where the tags array contains both "red" and "blue":
{ tags: { $all: "red", "blue" } }
What is the main issue with this query?
medium
A. The $all operator requires an array of values, not separate arguments.
B. The query should use $elemMatch instead of $all.
C. The field name should be inside quotes.
D. The query is missing a $and operator.
Solution
Step 1: Understand $all operator syntax
The $all operator expects an array of values to match all elements inside the array field.
Step 2: Identify the syntax error in the query
The query incorrectly passes separate arguments to $all instead of an array. Correct syntax is { tags: { $all: ["red", "blue"] } }.
Final Answer:
The $all operator requires an array of values, not separate arguments. -> Option A
Quick Check:
$all needs array syntax = A [OK]
Hint: Use array syntax with $all operator [OK]
Common Mistakes:
Passing multiple values without array brackets
Confusing $all with $elemMatch
Ignoring syntax errors in operator usage
5. You want to find documents where the ratings array contains at least one element greater than 4 and less than 7. Which query correctly uses $elemMatch to achieve this?
Step 1: Understand $elemMatch usage for multiple conditions on array elements
$elemMatch allows specifying multiple conditions that must be true for the same array element.
Step 2: Analyze each option for correctness
{ ratings: { $elemMatch: { $gt: 4, $lt: 7 } } } correctly uses $elemMatch with $gt and $lt to find elements >4 and <7. { ratings: { $gt: 4, $lt: 7 } } is invalid syntax because $gt and $lt cannot be used directly on the array field. { ratings: { $in: [5, 6] } } matches specific values but does not cover the range condition. { ratings: { $elemMatch: { $gte: 4, $lte: 7 } } } uses $gte and $lte which includes 4 and 7, not strictly greater and less.