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

CategoryComparison
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ <field>: { $nin: [ <value1>, <value2>, ... ] } }

⚙️ Parameters

fieldThe document field to match.
values arrayThe 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

📚 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏