$nin (Not In Array)
Last updated: 2026-10-09
$nin (Not In Array)
$nin selects documents where the field value does not equal any value in the given array — the negation of $in. `{ age: { $nin: [18, 21] } }` matches users aged neither 18 nor 21. Like $ne it does not match documents missing the field; on array fields it matches when any element is not in the array.
| Category | Comparison |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ <field>: { $nin: [ <value1>, <value2>, ... ] } }
⚙️ Parameters
| field | The document field to match. |
|---|---|
| values array | The list of values to exclude; the field must equal none of them. |
Returns:Cursor of matching documents
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $nin: exclude users aged 18 and 21
db.users.find({ age: { $nin: [18, 21] } })
// Documents missing the field are not returned
db.users.find({ age: { $nin: [18] } })
Output:
// Returns users whose age is neither 18 nor 21; missing-field documents are excluded
📌 Notes
- Does not match documents missing the field; combine with $exists to include them
- On array fields, matches when any element is not in the array
- Use $ne for one value, $nin for a whole list
🏷️ Related Tags
💡 Related Cases
Document Query Basics: The `find` Method and Projections
Query Operators: A Complete Guide to the 30+ Operator
📚 Related Tutorials
❓ FAQ
QWhat is the difference between $nin and $ne?
A$ne excludes one value, $nin excludes a list; both mean not-equal, $nin is the bulk form.
QDoes $nin return documents where the field does not exist?
ANo. Like $ne, $nin matches only documents where the field exists and its value is not in the array.
QHow does $nin match array fields?
AIt matches when any single element is not in the given array, not the whole array at once.