Bird
Raised Fist0
MongoDBquery~20 mins

$in for matching a set 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
🎖️
MongoDB $in Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
Find documents where a field matches any value in a set
Given a collection products with documents containing a category field, which query returns all products whose category is either 'electronics', 'books', or 'clothing'?
MongoDB
db.products.find({ category: { $in: ['electronics', 'books', 'clothing'] } })
AReturns products with category exactly matching the array ['electronics', 'books', 'clothing']
BReturns all products with category 'electronics', 'books', or 'clothing'
CReturns products with category not in 'electronics', 'books', or 'clothing'
DReturns all products regardless of category
Attempts:
2 left
💡 Hint
Think about how $in matches any value inside the array.
query_result
intermediate
2:00remaining
Using $in with numeric values
Consider a collection orders where each document has a numeric status_code. Which query returns orders with status codes 1, 3, or 5?
MongoDB
db.orders.find({ status_code: { $in: [1, 3, 5] } })
AReturns all orders regardless of status_code
BReturns orders with status_code exactly equal to the array [1, 3, 5]
CReturns orders with status_code 1, 3, or 5
DReturns orders with status_code not equal to 1, 3, or 5
Attempts:
2 left
💡 Hint
Remember $in checks if the field value is in the array.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in $in usage
Which of the following MongoDB queries has a syntax error when using $in to match the tags field?
Adb.collection.find({ tags: { $in: 'red', 'blue', 'green' } })
Bdb.collection.find({ tags: { $in: ['red', 'blue', 'green'] } })
C)} } ]'neerg' ,'eulb' ,'der'[ :ni$ { :sgat {(dnif.noitcelloc.bd
Ddb.collection.find({ tags: { $in: ['red'] } })
Attempts:
2 left
💡 Hint
Check how the array is passed to $in.
optimization
advanced
2:00remaining
Optimizing queries with $in on indexed fields
You have a large collection users with an index on the role field. Which query will best use the index to find users with roles 'admin', 'editor', or 'viewer'?
Adb.users.find({ $or: [{ role: 'admin' }, { role: 'editor' }, { role: 'viewer' }] })
Bdb.users.find({ role: { $all: ['admin', 'editor', 'viewer'] } })
Cdb.users.find({ role: { $nin: ['admin', 'editor', 'viewer'] } })
Ddb.users.find({ role: { $in: ['admin', 'editor', 'viewer'] } })
Attempts:
2 left
💡 Hint
Think about how $in uses indexes compared to $or.
🧠 Conceptual
expert
3:00remaining
Understanding $in behavior with arrays in documents
In a collection posts, each document has a field tags which is an array of strings. What does the query db.posts.find({ tags: { $in: ['mongodb', 'database'] } }) return?
ADocuments where the tags array contains at least one of 'mongodb' or 'database'
BDocuments where the tags array exactly matches ['mongodb', 'database']
CDocuments where the tags array contains both 'mongodb' and 'database'
DDocuments where the tags array contains neither 'mongodb' nor 'database'
Attempts:
2 left
💡 Hint
Remember how $in works with array fields in documents.

Practice

(1/5)
1.

What does the $in operator do in MongoDB queries?

easy
A. Deletes documents matching a condition
B. Finds documents where a field is greater than a value
C. Updates documents by adding new fields
D. Finds documents where a field matches any value in a given list

Solution

  1. Step 1: Understand the purpose of $in

    The $in operator is used to match documents where a field's value is equal to any value in a specified array.
  2. Step 2: Compare with other options

    Options B, C, and D describe different MongoDB operations unrelated to $in.
  3. Final Answer:

    Finds documents where a field matches any value in a given list -> Option D
  4. Quick Check:

    $in matches any value in list [OK]
Hint: Remember: $in checks if field is in a list [OK]
Common Mistakes:
  • Confusing $in with comparison operators like $gt
  • Thinking $in updates or deletes documents
  • Using $in without an array of values
2.

Which of the following is the correct syntax to find documents where the field color is either "red", "blue", or "green"?

{ color: { $in: ["red", "blue", "green"] } }
easy
A. { color: { $in: ["red", "blue", "green"] } }
B. { color: { $in: "red", "blue", "green" } }
C. { color: { $in: "red|blue|green" } }
D. { color: { $in: { "red", "blue", "green" } } }

Solution

  1. Step 1: Check the correct use of $in syntax

    The $in operator requires an array of values inside square brackets []. { color: { $in: ["red", "blue", "green"] } } correctly uses an array with strings.
  2. Step 2: Identify syntax errors in other options

    { color: { $in: "red", "blue", "green" } } misses brackets for the array. { color: { $in: "red|blue|green" } } uses a string with pipes instead of an array. { color: { $in: { "red", "blue", "green" } } } uses curly braces which is invalid for arrays.
  3. Final Answer:

    { color: { $in: ["red", "blue", "green"] } } -> Option A
  4. Quick Check:

    $in needs an array [OK]
Hint: Always use square brackets [] for $in values [OK]
Common Mistakes:
  • Using strings instead of arrays for $in
  • Using curly braces {} instead of square brackets []
  • Separating values with commas but missing brackets
3.

Given the collection products with documents:

[{ "name": "Pen", "category": "stationery" }, { "name": "Apple", "category": "fruit" }, { "name": "Notebook", "category": "stationery" }, { "name": "Banana", "category": "fruit" }]

What will be the result of this query?

db.products.find({ category: { $in: ["fruit"] } })
medium
A. [{ "name": "Pen", "category": "stationery" }, { "name": "Notebook", "category": "stationery" }]
B. [{ "name": "Apple", "category": "fruit" }, { "name": "Banana", "category": "fruit" }]
C. []
D. All documents in the collection

Solution

  1. Step 1: Understand the query filter

    The query filters documents where the category field is in the array ["fruit"]. This means only documents with category "fruit" will match.
  2. Step 2: Identify matching documents

    Documents with "Apple" and "Banana" have category "fruit", so they are returned. Others are excluded.
  3. Final Answer:

    [{ "name": "Apple", "category": "fruit" }, { "name": "Banana", "category": "fruit" }] -> Option B
  4. Quick Check:

    Filter by category in ["fruit"] returns fruit items [OK]
Hint: Match only documents with field in the given list [OK]
Common Mistakes:
  • Expecting documents with other categories to appear
  • Confusing $in with $nin (not in)
  • Thinking $in matches substrings instead of exact values
4.

What is wrong with this MongoDB query?

db.users.find({ age: { $in: 25, 30, 35 } })
medium
A. The query should use $nin instead of $in
B. The field name age is invalid
C. The $in operator requires an array of values, not separate arguments
D. The query is correct and will return matching documents

Solution

  1. Step 1: Check the syntax of $in usage

    The $in operator expects a single array argument containing values to match. Here, values are passed as separate arguments, which is invalid syntax.
  2. Step 2: Identify the correct syntax

    The correct syntax is { age: { $in: [25, 30, 35] } } with square brackets around the values.
  3. Final Answer:

    The $in operator requires an array of values, not separate arguments -> Option C
  4. Quick Check:

    $in needs an array [OK]
Hint: Always wrap $in values in square brackets [OK]
Common Mistakes:
  • Passing multiple values without an array
  • Confusing $in with other operators
  • Assuming query is valid without brackets
5.

You have a collection orders with documents containing a field status. You want to find all orders where the status is either "pending", "shipped", or "delivered" but exclude those with status "cancelled" or "returned". Which query correctly uses $in and $nin to achieve this?

hard
A. { $or: [ { status: { $in: ["pending", "shipped", "delivered"] } }, { status: { $nin: ["cancelled", "returned"] } } ] }
B. { status: { $in: ["pending", "shipped", "delivered"] }, status: { $nin: ["cancelled", "returned"] } }
C. { status: { $in: ["pending", "shipped", "delivered"] }, $nin: ["cancelled", "returned"] }
D. { status: { $in: ["pending", "shipped", "delivered"], $nin: ["cancelled", "returned"] } }

Solution

  1. Step 1: Understand the need to combine $in and $nin on the same field

    We want documents where status is in one list but not in another. MongoDB does not allow combining $in and $nin inside the same object for a field. Instead, both conditions must be combined using an implicit AND by specifying both in the query object.
  2. Step 2: Analyze each option's structure

    { status: { $in: ["pending", "shipped", "delivered"] }, status: { $nin: ["cancelled", "returned"] } } uses the same field key twice with different operators, which is invalid JSON syntax. { $or: [ { status: { $in: ["pending", "shipped", "delivered"] } }, { status: { $nin: ["cancelled", "returned"] } } ] } uses $or, which applies OR logic, not the required AND. { status: { $in: ["pending", "shipped", "delivered"] }, $nin: ["cancelled", "returned"] } places $nin outside the field, which is invalid. { status: { $in: ["pending", "shipped", "delivered"], $nin: ["cancelled", "returned"] } } tries to combine $in and $nin inside the same object, which is invalid in MongoDB.
  3. Step 3: Correct approach

    The correct way is to combine both conditions using $and or by specifying both operators inside an object using $and or by using the implicit AND by combining conditions in the query object like: { status: { $in: [...] }, status: { $nin: [...] } } is invalid JSON because keys repeat. So the correct query is:
    { status: { $in: [...] }, status: { $nin: [...] } } is invalid.
    Instead, use:
    { status: { $in: [...] }, status: { $nin: [...] } } is invalid.
    So the correct way is:
    { status: { $in: [...] }, $nin: [...] } is invalid.
    Therefore, the correct query is:
    { status: { $in: [...] }, $nin: [...] } is invalid.
    Hence, the only valid way is to use $and operator:
    { $and: [ { status: { $in: [...] } }, { status: { $nin: [...] } } ] }
  4. Final Answer:

    { $and: [ { status: { $in: ["pending", "shipped", "delivered"] } }, { status: { $nin: ["cancelled", "returned"] } } ] } -> Option A (modified)
  5. Quick Check:

    Use $and to combine $in and $nin conditions [OK]
Hint: Use $and to combine multiple conditions on the same field [OK]
Common Mistakes:
  • Repeating the same field key multiple times in query
  • Placing $nin outside the field object
  • Using separate objects for the same field without $and