Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

operator
mongodb
$ne
communitycreator

What is the $ne operator in MongoDB?

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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
$ne
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring