0
0
MongoDBquery~5 mins

$nin for not in set in MongoDB

Choose your learning style9 modes available
Introduction

Use $nin to find items that do NOT match any value in a list. It helps exclude unwanted data.

You want to find all products except those in certain categories.
You need to get users who are not from specific cities.
You want to exclude certain tags from search results.
You want to filter out orders that have specific statuses.
You want to find documents where a field's value is not in a given set.
Syntax
MongoDB
{ 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.

Examples
Finds documents where category is NOT 'electronics' or 'furniture'.
MongoDB
{ category: { $nin: ['electronics', 'furniture'] } }
Finds documents where age is not 20, 30, or 40.
MongoDB
{ age: { $nin: [20, 30, 40] } }
Finds documents where status is neither 'pending' nor 'cancelled'.
MongoDB
{ status: { $nin: ['pending', 'cancelled'] } }
Sample Program

This query finds all orders where the status is NOT 'shipped' or 'delivered'.

MongoDB
db.orders.find({ status: { $nin: ['shipped', 'delivered'] } })
OutputSuccess
Important Notes

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.

Summary

$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.