Bird
Raised Fist0
MongoDBquery~10 mins

$nin for not in set in MongoDB - Step-by-Step Execution

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
Concept Flow - $nin for not in set
Start Query
Check each document's field
Is field value NOT in $nin array?
NoExclude document
Yes
Include document in result
Repeat for all documents
Return filtered documents
The query checks each document's field value and includes it only if the value is NOT in the given $nin array.
Execution Sample
MongoDB
db.collection.find({ age: { $nin: [20, 30, 40] } })
Finds documents where the age is NOT 20, 30, or 40.
Execution Table
StepDocumentField Value (age)Check $nin ConditionInclude in Result?
1{_id:1, age:25}2525 NOT in [20,30,40] -> TrueYes
2{_id:2, age:30}3030 NOT in [20,30,40] -> FalseNo
3{_id:3, age:35}3535 NOT in [20,30,40] -> TrueYes
4{_id:4, age:40}4040 NOT in [20,30,40] -> FalseNo
5{_id:5, age:50}5050 NOT in [20,30,40] -> TrueYes
6All documents checked--Query ends
💡 All documents checked; only those with age NOT in [20,30,40] included.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5Final
Current DocumentNone{_id:1, age:25}{_id:2, age:30}{_id:3, age:35}{_id:4, age:40}{_id:5, age:50}None
Included in ResultNoYesNoYesNoYesYes documents: {_id:1,3,5}
Key Moments - 2 Insights
Why is the document with age 30 excluded even though 30 is a number?
Because $nin means 'NOT in' the given array. Since 30 is in [20,30,40], it fails the condition and is excluded (see execution_table step 2).
What happens if the field is missing in a document?
Documents missing the field are included because their field value is considered undefined, which is not in the $nin array (not shown in this example but important to know).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, which document is included at step 3?
A{_id:4, age:40}
B{_id:3, age:35}
C{_id:2, age:30}
D{_id:5, age:50}
💡 Hint
Check the 'Include in Result?' column at step 3 in the execution_table.
At which step does the condition become false?
AStep 3
BStep 1
CStep 2
DStep 5
💡 Hint
Look for 'False' in the 'Check $nin Condition' column in the execution_table.
If we add 50 to the $nin array, what happens to the document at step 5?
AIt is excluded from the result
BIt is included in the result
CIt causes an error
DIt is included only if age is 50
💡 Hint
Refer to how $nin excludes values present in its array, as shown in the execution_table.
Concept Snapshot
$nin operator filters documents where the field's value is NOT in the specified array.
Syntax: { field: { $nin: [value1, value2, ...] } }
Includes documents with field values outside the array.
Missing fields are included by default.
Useful to exclude multiple values in one query.
Full Transcript
This visual execution shows how MongoDB's $nin operator works. The query checks each document's field value against an array of excluded values. If the value is NOT in the array, the document is included in the result. For example, with $nin: [20,30,40], documents with age 25, 35, and 50 are included, while those with 30 and 40 are excluded. The execution table traces each document step-by-step, showing the condition check and inclusion decision. Key points include understanding that $nin excludes values inside the array and includes missing fields. The quiz reinforces these ideas by asking about specific steps and changes to the $nin array.

Practice

(1/5)
1. What does the MongoDB operator $nin do in a query?
easy
A. Selects documents where the field's value is in the specified array
B. Selects documents where the field's value is NOT in the specified array
C. Updates documents with values in the specified array
D. Deletes documents where the field's value is in the specified array

Solution

  1. Step 1: Understand the purpose of $nin

    The $nin operator is used to filter documents where a field's value is NOT included in a given list of values.
  2. Step 2: Compare with other operators

    Unlike $in which selects values inside the array, $nin excludes those values.
  3. Final Answer:

    Selects documents where the field's value is NOT in the specified array -> Option B
  4. Quick Check:

    $nin excludes values = B [OK]
Hint: Remember: $nin means NOT in list [OK]
Common Mistakes:
  • Confusing $nin with $in
  • Thinking it updates or deletes documents
  • Using it to select values inside the array
2. Which of the following is the correct syntax to find documents where the field status is NOT 'active' or 'pending' using $nin?
easy
A. { status: { $nin: ['active', 'pending'] } }
B. { status: { $nin: 'active', 'pending' } }
C. { status: { $nin: ['active'] || ['pending'] } }
D. { status: { $nin: 'active' && 'pending' } }

Solution

  1. Step 1: Check the correct $nin syntax

    The $nin operator requires an array of values inside square brackets to specify the excluded set.
  2. 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.
  3. Final Answer:

    { status: { $nin: ['active', 'pending'] } } -> Option A
  4. Quick Check:

    Correct array syntax for $nin = A [OK]
Hint: Use square brackets for arrays in $nin [OK]
Common Mistakes:
  • Using multiple arguments instead of an array
  • Using logical operators inside $nin
  • Missing square brackets around values
3. Given the collection 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'] } })
medium
A. All documents returned
B. [{ name: 'Apple', category: 'fruit' }, { name: 'Carrot', category: 'vegetable' }]
C. [] (empty array)
D. [{ name: 'Pen', category: 'stationery' }, { name: 'Notebook', category: 'stationery' }]

Solution

  1. Step 1: Understand the $nin filter

    The query excludes documents where category is 'fruit' or 'vegetable'.
  2. Step 2: Identify matching documents

    Documents with category 'stationery' are not in ['fruit', 'vegetable'], so they match. 'Pen' and 'Notebook' have 'stationery'.
  3. Final Answer:

    [{ name: 'Pen', category: 'stationery' }, { name: 'Notebook', category: 'stationery' }] -> Option D
  4. Quick Check:

    Exclude 'fruit' and 'vegetable' = stationery items only [OK]
Hint: Exclude unwanted categories with $nin array [OK]
Common Mistakes:
  • Confusing $nin with $in
  • Expecting documents with excluded categories
  • Assuming empty result when some match
4. You wrote this query to exclude users with roles 'admin' or 'moderator':
db.users.find({ role: { $nin: 'admin', 'moderator' } })

But it throws an error. What is the problem?
medium
A. The $nin operator requires an array, not multiple arguments
B. The field name role is misspelled
C. The query should use $in instead of $nin
D. MongoDB does not support $nin operator

Solution

  1. Step 1: Check $nin syntax

    $nin expects a single array argument listing values to exclude.
  2. Step 2: Identify the error in the query

    The query passes two separate string arguments instead of one array, causing syntax error.
  3. Final Answer:

    The $nin operator requires an array, not multiple arguments -> Option A
  4. Quick Check:

    $nin needs array input = C [OK]
Hint: Always wrap values in an array for $nin [OK]
Common Mistakes:
  • Passing multiple arguments instead of an array
  • Using wrong operator $in by mistake
  • Assuming $nin is unsupported
5. You have a collection 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?
hard
A. { status: { $nin: ['pending', 'cancelled'] }, orderId: { $ne: 4 } }
B. { status: { $nin: ['pending', 'cancelled', 4] } }
C. { status: { $nin: ['pending', 'cancelled'] }, orderId: { $nin: [4] } }
D. { status: { $nin: ['pending', 'cancelled'] }, orderId: { $in: [4] } }

Solution

  1. Step 1: Exclude statuses 'pending' and 'cancelled'

    Use { status: { $nin: ['pending', 'cancelled'] } } to exclude these statuses.
  2. Step 2: Exclude orderId 4 using $nin

    Use { orderId: { $nin: [4] } } to exclude orderId 4 as well.
  3. Step 3: Combine conditions

    Both conditions together filter out unwanted statuses and orderId 4.
  4. Final Answer:

    { status: { $nin: ['pending', 'cancelled'] }, orderId: { $nin: [4] } } -> Option C
  5. Quick Check:

    Use $nin on both fields = A [OK]
Hint: Use separate $nin for each field to exclude multiple sets [OK]
Common Mistakes:
  • Putting orderId inside status array
  • Using $ne instead of $nin for multiple values
  • Using $in to exclude values