$ne
On this page
$ne
$ne
selects the documents where the value of the specified field is not equal to the specified value. This includes documents that do not contain the specified field.For comparison of different BSON type values, see the specified BSON comparison order.
Compatibility
You can use $ne
for deployments hosted in the following
environments:
MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
MongoDB Enterprise: The subscription-based, self-managed version of MongoDB
MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB
Syntax
The $ne
operator has the following form:
{ field: { $ne: value } }
Examples
db.inventory.find( { qty: { $ne: 20 } } )
This query will select all documents in the inventory
collection
where the qty
field value does not equal 20
,
including those documents that do not contain the qty
field.
Consider the following example which uses the $ne
operator with a field in an embedded document:
db.inventory.update( { "carrier.state": { $ne: "NY" } }, { $set: { qty: 20 } } )
This update()
operation will set
the qty
field value in the documents that contain the embedded
document carrier
whose state
field value does not equal "NY",
or where the state
field or the carrier
embedded document
do not exist.
The inequality operator $ne
is not very selective since
it often matches a large portion of the index. As a result, in many
cases, a $ne
query with an index may perform no better
than a $ne
query that must scan all documents in a
collection. See also Query Selectivity.