How to Use $nin Operator in MongoDB Queries
In MongoDB, use the
$nin operator to find documents where a field's value is not in a specified list of values. It works like saying "not in" for filtering data. For example, { field: { $nin: [value1, value2] } } returns documents where field is neither value1 nor value2.Syntax
The $nin operator takes an array of values and matches documents where the field's value is not in that array.
Syntax parts:
field: The document field to check.$nin: The operator specifying "not in".[value1, value2, ...]: Array of values to exclude.
json
{ field: { $nin: [value1, value2, value3] } }Example
This example finds all documents in the products collection where the category is not "electronics" or "clothing".
mongodb
db.products.find({ category: { $nin: ["electronics", "clothing"] } })Output
[
{ "_id": 3, "name": "Book", "category": "books" },
{ "_id": 4, "name": "Pen", "category": "stationery" }
]
Common Pitfalls
Common mistakes when using $nin include:
- Using
$ninwith a non-array value, which causes errors. - Confusing
$ninwith$ne(not equal), which only excludes one value. - Not considering that
$ninalso matches documents where the field isnullor missing.
Example of wrong and right usage:
mongodb
/* Wrong: $nin value is not an array */ db.collection.find({ status: { $nin: "active" } }) /* Right: $nin value is an array */ db.collection.find({ status: { $nin: ["active"] } })
Quick Reference
| Operator | Description | Example |
|---|---|---|
| $nin | Matches values not in the given array | { field: { $nin: [1, 2, 3] } } |
| $ne | Matches values not equal to a single value | { field: { $ne: 1 } } |
| $in | Matches values in the given array | { field: { $in: [1, 2, 3] } } |
Key Takeaways
Use $nin with an array to exclude multiple values from query results.
$nin matches documents where the field is missing or null as well.
Always provide an array to $nin; a single value causes errors.
$nin is different from $ne, which excludes only one value.
Test queries to ensure $nin behaves as expected with your data.