What is the $ne operator in MongoDB?

Overview

In MongoDB, the $ne operator signifies the not-equal operator. It is one of the comparison operators in MongoDB. It is used to match the documents whose field value is not equal to the one specified by the $ne operator.

Syntax

{field: {$ne: value}

Parameters

  • field: This is a valid document path.

  • value: This is the specified value that will match the field values that are not equal to it.

Return value

This will return the documents whose field value does not match the specified value.

Example

In the fruit collection shown below, which contains the following documents, we will use $ne to match the documents whose quantity is not equal to 20:

{
     "_id" : ObjectId("60f0553e1cd9041c4014a2a3"),
     "name": "apple",
     "quantity": 20
}
{
     "_id" : ObjectId("60fd8fb788fe0e2118ddbd7c"),   
     "name": "mango",
     "quantity": 20
}
{
     "_id" : ObjectId("6120216fbb75d313c4d65af4"),    
     "name": "watermelon",
     "quantity": 10
}
{
     "_id" : ObjectId("6120216fbb75d313c4d34cd3"),    
     "name": "orange",
     "quantity": 15
}

Now, let’s match the documents whose quantity field is not equal to 20. We will do this with the help of the $ne operator:

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

The output will be as follows:

{
     "_id" : ObjectId("6120216fbb75d313c4d65af4"),    
     "name": "watermelon",
     "quantity": 10
}
{
     "_id" : ObjectId("6120216fbb75d313c4d34cd3"),    
     "name": "orange",
     "quantity": 15
}

Code explanation

From the result shown above, only two documents were returned. This is because when we called the $ne query operator, we asked it to match the documents whose quantity field was not equal to 20. In the fruits collection, there were only two documents whose quantity fields were equal to 20.

New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources