Docs Menu

Docs HomeDevelop ApplicationsMongoDB Manual

$ne

On this page

  • Compatibility
  • Syntax
  • Examples
  • Match Document Fields That Are Not Equal
  • Update Based on Not Equal Embedded Document Fields
  • Learn More
$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.

You can use $ne for deployments hosted in the following environments:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud

The $ne operator has the following form:

{ field: { $ne: value } }

Note

If the value of the $ne operator is null, see Non-Equality Filter for more information.

The following examples use the inventory collection. To create the collection run the following insertMany() command in mongo:

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 }
}
] )

Select all documents in the inventory collection where quantity is not equal to 20. This query also selects documents that do not have the quantity field:

db.inventory.find( { quantity: { $ne: 20 } } )

The SQL equivalent to this query is:

SELECT * FROM INVENTORY WHERE QUANTITIY != 20

The following example sets the price field based on a $ne comparison against a field in an embedded document. The updateMany() operation searches for an embedded document, carrier, with a subfield named fee. It uses $set to update the price field to 9.99 in each document where fee has a value that does not equal 1 or where the fee subfield does not exist:

db.inventory.updateMany(
{ "carrier.fee" : { $ne: 1 } },
{ $set: { "price": 9.99 } }
)

The SQL equivalent to this query is:

UPDATE INVENTORY SET PRICE = '9.99' WHERE carrierfee != 1

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.

←  $lte$nin →