$ne
On this page
Definition
$ne
Syntax:
{ field: { $ne: value } }
$ne
selects the documents where the value of thefield
is not equal to the specifiedvalue
. This includes documents that do not contain thefield
.For comparison of different BSON type values, see the specified BSON comparison order.
Examples
The following examples use the inventory
collection. Create the
collection:
db.inventory.insertMany( [ { "item": "nuts", "quantity": 30, "carrier": { "name": "Shipit", "fee": 3 } }, { "item": "bolts", "quantity": 50, "carrier": { "name": "Shipit", "fee": 4 } }, { "item": "washers", "quantity": 10, "carrier": { "name": "Shipit", "fee": 1 } } ] )
Match Document Fields
Select all documents in the inventory
collection where quantity
is not equal to 20
:
db.inventory.find( { quantity: { $ne: 20 } } )
The query will also select documents that do not have the quantity
field.
Example output:
{ _id: ObjectId("61ba667dfe687fce2f042420"), item: 'nuts', quantity: 30, carrier: { name: 'Shipit', fee: 3 } }, { _id: ObjectId("61ba667dfe687fce2f042421"), item: 'bolts', quantity: 50, carrier: { name: 'Shipit', fee: 4 } }, { _id: ObjectId("61ba667dfe687fce2f042422"), item: 'washers', quantity: 10, carrier: { name: 'Shipit', fee: 1 } }
Perform an Update Based on Embedded Document Fields
The following example sets the price
field based on a $ne
comparison against a field in an embedded document.
db.inventory.updateMany( { "carrier.fee": { $ne: 1 } }, { $set: { "price": 9.99 } } )
Example output:
{ _id: ObjectId("61ba66e2fe687fce2f042423"), item: 'nuts', quantity: 30, carrier: { name: 'Shipit', fee: 3 }, price: 9.99 }, { _id: ObjectId("61ba66e2fe687fce2f042424"), item: 'bolts', quantity: 50, carrier: { name: 'Shipit', fee: 4 }, price: 9.99 }, { _id: ObjectId("61ba66e2fe687fce2f042425"), item: 'washers', quantity: 10, carrier: { name: 'Shipit', fee: 1 } }
This updateMany()
operation searches for an
embedded document, carrier
, with a subfield named fee
. It sets
{ price: 9.99 }
in each document where fee
has a value that
does not equal 1 or where the fee
subfield does 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.