How to Use $nor Operator in MongoDB Queries
In MongoDB, the
$nor operator is used to select documents that fail all the given conditions inside an array. It works like a logical NOR, returning documents where none of the specified criteria are true.Syntax
The $nor operator takes an array of query expressions and returns documents that do not match any of these expressions.
Each element inside the array is a condition that MongoDB tests against the documents.
json
{
$nor: [
{ <field1>: <condition1> },
{ <field2>: <condition2> },
...
]
}Example
This example shows how to find documents in a collection where the status is neither "A" nor "D".
mongodb
db.orders.find({
$nor: [
{ status: "A" },
{ status: "D" }
]
})Output
[
{ "_id": 3, "item": "notebook", "status": "P" },
{ "_id": 4, "item": "pen", "status": "C" }
]
Common Pitfalls
- Using
$norwith an empty array returns all documents because no conditions are negated. - Confusing
$norwith$not:$norworks with multiple conditions, while$notnegates a single condition. - Not wrapping each condition inside its own object in the array causes syntax errors.
mongodb
/* Wrong usage: conditions not wrapped in objects */ db.orders.find({ $nor: [ { status: "A" }, { status: "D" } ] }) /* Correct usage: each condition is an object */ db.orders.find({ $nor: [ { status: "A" }, { status: "D" } ] })
Quick Reference
| Operator | Description | Example |
|---|---|---|
| $nor | Selects documents that fail all given conditions | { $nor: [ { age: { $lt: 18 } }, { status: "inactive" } ] } |
| $not | Negates a single condition | { age: { $not: { $gt: 30 } } } |
Key Takeaways
Use
$nor to find documents that do not match any of the specified conditions.Each condition inside
$nor must be an object wrapped in an array.$nor is different from $not; it works with multiple conditions.An empty
$nor array matches all documents because no conditions are negated.Test queries carefully to avoid syntax errors with
$nor usage.