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.
{field: {$ne: value}
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.
This will return the documents whose field value does not match the specified value.
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
}
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
.