$nin for not in set in MongoDB - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When using $nin in MongoDB, we want to know how the time to find documents changes as the data grows.
We ask: How does checking for values not in a list affect the work MongoDB does?
Analyze the time complexity of the following code snippet.
db.collection.find({
field: { $nin: ["A", "B", "C"] }
})
.limit(100)
This query finds documents where the field value is not in the list ["A", "B", "C"].
Look at what MongoDB does repeatedly to answer this query.
- Primary operation: Checking each document's
fieldvalue against the$ninlist. - How many times: Once for each document scanned until 100 matches are found.
As the number of documents grows, MongoDB checks more documents to find those not in the list.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows roughly in direct proportion to the number of documents MongoDB scans.
Time Complexity: O(n)
This means the time to run the query grows linearly with the number of documents MongoDB checks.
[X] Wrong: "Using $nin is always fast because it just excludes a few values."
[OK] Correct: MongoDB may need to check many documents to confirm they are not in the list, especially without an index, so it can take time proportional to the data size.
Understanding how $nin affects query time helps you explain real database behavior clearly and shows you think about efficiency in practical ways.
"What if we added an index on the field? How would the time complexity change?"
Practice
$nin do in a query?Solution
Step 1: Understand the purpose of
The$nin$ninoperator is used to filter documents where a field's value is NOT included in a given list of values.Step 2: Compare with other operators
Unlike$inwhich selects values inside the array,$ninexcludes those values.Final Answer:
Selects documents where the field's value is NOT in the specified array -> Option BQuick Check:
$ninexcludes values = B [OK]
$nin means NOT in list [OK]- Confusing
$ninwith$in - Thinking it updates or deletes documents
- Using it to select values inside the array
status is NOT 'active' or 'pending' using $nin?Solution
Step 1: Check the correct
The$ninsyntax$ninoperator requires an array of values inside square brackets to specify the excluded set.Step 2: Validate each option
{ status: { $nin: ['active', 'pending'] } } correctly uses an array with two strings. Options B, C, and D have syntax errors or invalid expressions.Final Answer:
{ status: { $nin: ['active', 'pending'] } } -> Option AQuick Check:
Correct array syntax for$nin= A [OK]
$nin [OK]- Using multiple arguments instead of an array
- Using logical operators inside
$nin - Missing square brackets around values
products with documents:{ name: 'Pen', category: 'stationery' }{ name: 'Apple', category: 'fruit' }{ name: 'Notebook', category: 'stationery' }{ name: 'Carrot', category: 'vegetable' }What will be the result of this query?
db.products.find({ category: { $nin: ['fruit', 'vegetable'] } })Solution
Step 1: Understand the
The query excludes documents where$ninfiltercategoryis 'fruit' or 'vegetable'.Step 2: Identify matching documents
Documents with category 'stationery' are not in ['fruit', 'vegetable'], so they match. 'Pen' and 'Notebook' have 'stationery'.Final Answer:
[{ name: 'Pen', category: 'stationery' }, { name: 'Notebook', category: 'stationery' }] -> Option DQuick Check:
Exclude 'fruit' and 'vegetable' = stationery items only [OK]
$nin array [OK]- Confusing
$ninwith$in - Expecting documents with excluded categories
- Assuming empty result when some match
db.users.find({ role: { $nin: 'admin', 'moderator' } })But it throws an error. What is the problem?
Solution
Step 1: Check
$ninsyntax$ninexpects a single array argument listing values to exclude.Step 2: Identify the error in the query
The query passes two separate string arguments instead of one array, causing syntax error.Final Answer:
The$ninoperator requires an array, not multiple arguments -> Option AQuick Check:
$ninneeds array input = C [OK]
$nin [OK]- Passing multiple arguments instead of an array
- Using wrong operator
$inby mistake - Assuming
$ninis unsupported
orders with documents:{ orderId: 1, status: 'shipped' }{ orderId: 2, status: 'pending' }{ orderId: 3, status: 'cancelled' }{ orderId: 4, status: 'delivered' }You want to find orders NOT in statuses 'pending' or 'cancelled' AND exclude orders with
orderId 4. Which query correctly uses $nin to achieve this?Solution
Step 1: Exclude statuses 'pending' and 'cancelled'
Use{ status: { $nin: ['pending', 'cancelled'] } }to exclude these statuses.Step 2: Exclude orderId 4 using
Use$nin{ orderId: { $nin: [4] } }to exclude orderId 4 as well.Step 3: Combine conditions
Both conditions together filter out unwanted statuses and orderId 4.Final Answer:
{ status: { $nin: ['pending', 'cancelled'] }, orderId: { $nin: [4] } } -> Option CQuick Check:
Use$ninon both fields = A [OK]
$nin for each field to exclude multiple sets [OK]- Putting orderId inside status array
- Using
$neinstead of$ninfor multiple values - Using
$into exclude values
