Trusted answers to developer questions

What is the $ne operator in MongoDB?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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.

RELATED TAGS

operator
mongodb

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
Did you find this helpful?