How to Use $ne Operator in MongoDB for Not Equal Queries
In MongoDB, use the
$ne operator to find documents where a field's value is not equal to a specified value. It is used inside a query object like { field: { $ne: value } } to exclude matching values.Syntax
The $ne operator is used inside a query to specify that a field's value should not be equal to a given value.
- field: The name of the field to check.
- $ne: The operator meaning 'not equal'.
- value: The value that the field should not match.
json
{ field: { $ne: value } }Example
This example finds all documents in the users collection where the status field is not equal to "active".
mongodb
db.users.find({ status: { $ne: "active" } })Output
[
{ "_id": 1, "name": "Alice", "status": "inactive" },
{ "_id": 3, "name": "Charlie", "status": "pending" }
]
Common Pitfalls
Common mistakes when using $ne include:
- Using
$neoutside a query object or without a field name. - Expecting
$neto exclude documents where the field is missing; it only excludes documents where the field equals the value. - Confusing
$newith$nin, which checks for values not in an array.
mongodb
/* Wrong: $ne used without field name */ db.users.find({ $ne: "active" }) /* Right: $ne used with field name */ db.users.find({ status: { $ne: "active" } })
Quick Reference
| Operator | Description | Example |
|---|---|---|
| $ne | Matches values not equal to specified value | { age: { $ne: 30 } } |
| $nin | Matches values not in specified array | { status: { $nin: ["active", "pending"] } } |
| $eq | Matches values equal to specified value | { status: { $eq: "active" } } |
Key Takeaways
Use $ne inside a field query to find documents where the field value is not equal to a given value.
$ne does not exclude documents where the field is missing; it only excludes documents with the exact value.
Always specify the field name before $ne in your query object.
For multiple values exclusion, consider using $nin instead of multiple $ne conditions.
Test queries to ensure they return expected results, especially when fields may be missing.