$in for matching a set in MongoDB - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When using $in in MongoDB, we want to know how the time to find matching documents changes as the list of values grows.
We ask: How does the number of operations grow when the set inside $in gets bigger?
Analyze the time complexity of the following MongoDB query using $in.
db.collection.find({
field: { $in: [value1, value2, value3, ..., valueN] }
})
This query finds documents where the field matches any value in the given list.
Look at what repeats inside the query process.
- Primary operation: Checking if the document's field matches any value in the
$inlist. - How many times: Once for each document scanned, checking against the list of values.
As the list inside $in grows, the work to check each document grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Checking up to 10 values per document |
| 100 | Checking up to 100 values per document |
| 1000 | Checking up to 1000 values per document |
Pattern observation: The number of checks grows directly with the size of the $in list.
Time Complexity: O(n)
This means the time to match grows linearly with the number of values inside the $in list.
[X] Wrong: "Using $in with many values is always fast because MongoDB handles it internally."
[OK] Correct: MongoDB checks each value in the list, so a bigger list means more work and slower queries if no index supports it.
Understanding how $in scales helps you explain query performance clearly and shows you know how database operations grow with input size.
"What if we replaced $in with multiple $or conditions? How would the time complexity change?"
Practice
What does the $in operator do in MongoDB queries?
Solution
Step 1: Understand the purpose of
The$in$inoperator is used to match documents where a field's value is equal to any value in a specified array.Step 2: Compare with other options
Options B, C, and D describe different MongoDB operations unrelated to$in.Final Answer:
Finds documents where a field matches any value in a given list -> Option DQuick Check:
$inmatches any value in list [OK]
$in checks if field is in a list [OK]- Confusing
$inwith comparison operators like $gt - Thinking
$inupdates or deletes documents - Using
$inwithout an array of values
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"] } }Solution
Step 1: Check the correct use of
The$insyntax$inoperator requires an array of values inside square brackets []. { color: { $in: ["red", "blue", "green"] } } correctly uses an array with strings.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.Final Answer:
{ color: { $in: ["red", "blue", "green"] } } -> Option AQuick Check:
$inneeds an array [OK]
$in values [OK]- Using strings instead of arrays for
$in - Using curly braces {} instead of square brackets []
- Separating values with commas but missing brackets
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"] } })Solution
Step 1: Understand the query filter
The query filters documents where thecategoryfield is in the array ["fruit"]. This means only documents with category "fruit" will match.Step 2: Identify matching documents
Documents with "Apple" and "Banana" have category "fruit", so they are returned. Others are excluded.Final Answer:
[{ "name": "Apple", "category": "fruit" }, { "name": "Banana", "category": "fruit" }] -> Option BQuick Check:
Filter by category in ["fruit"] returns fruit items [OK]
- Expecting documents with other categories to appear
- Confusing $in with $nin (not in)
- Thinking $in matches substrings instead of exact values
What is wrong with this MongoDB query?
db.users.find({ age: { $in: 25, 30, 35 } })Solution
Step 1: Check the syntax of
The$inusage$inoperator expects a single array argument containing values to match. Here, values are passed as separate arguments, which is invalid syntax.Step 2: Identify the correct syntax
The correct syntax is{ age: { $in: [25, 30, 35] } }with square brackets around the values.Final Answer:
The$inoperator requires an array of values, not separate arguments -> Option CQuick Check:
$inneeds an array [OK]
$in values in square brackets [OK]- Passing multiple values without an array
- Confusing
$inwith other operators - Assuming query is valid without brackets
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?
Solution
Step 1: Understand the need to combine
We want documents where$inand$ninon the same fieldstatusis in one list but not in another. MongoDB does not allow combining$inand$nininside the same object for a field. Instead, both conditions must be combined using an implicit AND by specifying both in the query object.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$ninoutside the field, which is invalid. { status: { $in: ["pending", "shipped", "delivered"], $nin: ["cancelled", "returned"] } } tries to combine$inand$nininside the same object, which is invalid in MongoDB.Step 3: Correct approach
The correct way is to combine both conditions using$andor by specifying both operators inside an object using$andor 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$andoperator:{ $and: [ { status: { $in: [...] } }, { status: { $nin: [...] } } ] }Final Answer:
{ $and: [ { status: { $in: ["pending", "shipped", "delivered"] } }, { status: { $nin: ["cancelled", "returned"] } } ] } -> Option A (modified)Quick Check:
Use$andto combine$inand$ninconditions [OK]
- Repeating the same field key multiple times in query
- Placing
$ninoutside the field object - Using separate objects for the same field without $and
