Introduction
Use $nin to find items that do NOT match any value in a list. It helps exclude unwanted data.
Jump into concepts and practice - no test required
Use $nin to find items that do NOT match any value in a list. It helps exclude unwanted data.
{ field: { $nin: [value1, value2, ...] } }The $nin operator takes an array of values to exclude.
It matches documents where the field's value is not in the given array.
category is NOT 'electronics' or 'furniture'.{ category: { $nin: ['electronics', 'furniture'] } }age is not 20, 30, or 40.{ age: { $nin: [20, 30, 40] } }status is neither 'pending' nor 'cancelled'.{ status: { $nin: ['pending', 'cancelled'] } }This query finds all orders where the status is NOT 'shipped' or 'delivered'.
db.orders.find({ status: { $nin: ['shipped', 'delivered'] } })If the field does not exist in a document, that document will be included because its value is not in the list.
$nin is the opposite of $in, which finds values inside the list.
$nin helps exclude documents with certain values.
Use it when you want to filter out unwanted data from your results.
It works by matching documents where the field's value is NOT in the given array.
$nin do in a query?$nin$nin operator is used to filter documents where a field's value is NOT included in a given list of values.$in which selects values inside the array, $nin excludes those values.$nin excludes values = B [OK]$nin means NOT in list [OK]$nin with $instatus is NOT 'active' or 'pending' using $nin?$nin syntax$nin operator requires an array of values inside square brackets to specify the excluded set.$nin = A [OK]$nin [OK]$ninproducts with documents:{ name: 'Pen', category: 'stationery' }{ name: 'Apple', category: 'fruit' }{ name: 'Notebook', category: 'stationery' }{ name: 'Carrot', category: 'vegetable' }db.products.find({ category: { $nin: ['fruit', 'vegetable'] } })$nin filtercategory is 'fruit' or 'vegetable'.$nin array [OK]$nin with $indb.users.find({ role: { $nin: 'admin', 'moderator' } })$nin syntax$nin expects a single array argument listing values to exclude.$nin operator requires an array, not multiple arguments -> Option A$nin needs array input = C [OK]$nin [OK]$in by mistake$nin is unsupportedorders with documents:{ orderId: 1, status: 'shipped' }{ orderId: 2, status: 'pending' }{ orderId: 3, status: 'cancelled' }{ orderId: 4, status: 'delivered' }orderId 4. Which query correctly uses $nin to achieve this?{ status: { $nin: ['pending', 'cancelled'] } } to exclude these statuses.$nin{ orderId: { $nin: [4] } } to exclude orderId 4 as well.$nin on both fields = A [OK]$nin for each field to exclude multiple sets [OK]$ne instead of $nin for multiple values$in to exclude values