$ne Operator - (MongoDB Misc)
In MongoDB, the $ne
operator is a query operator that selects documents where the value of a field is not equal to the specified value.
Syntax
Here is the syntax for the $ne
operator in MongoDB:
{ field: { $ne: value } }
Example
Suppose we have a collection of products
documents with the following data:
{ "_id" : 1, "name" : "Product1", "category" : "CategoryA" }
{ "_id" : 2, "name" : "Product2", "category" : "CategoryB" }
{ "_id" : 3, "name" : "Product3", "category" : "CategoryA" }
{ "_id" : 4, "name" : "Product4", "category" : "CategoryB" }
Now, let's use the $ne
operator to find all documents where the "category"
field is not equal to "CategoryA"
:
db.products.find({ "category": { "$ne": "CategoryA" } })
The output of this query will be:
{ "_id" : 2, "name" : "Product2", "category" : "CategoryB" }
{ "_id" : 4, "name" : "Product4", "category" : "CategoryB" }
Explanation
The $ne
operator matches all documents where the field value is not equal to the specified value. In the example above, we searched for all documents where the "category"
field is not equal to "CategoryA"
, and the MongoDB query returned documents where "category"
is equal to "CategoryB"
. The operator can be used with any valid value for the specified field.
Use
The $ne
operator is used to retrieve documents where a specific field is not equal to a certain value. This operator is useful in situations where you need to exclude certain documents from your query and return only those that match your criteria.
Important Points
- The
$ne
operator is case sensitive. - You can use the
$ne
operator with any valid value for the specified field. - The
$ne
operator can be used with other logical operators like$and
and$or
.
Summary
In this page, we discussed the $ne
operator in MongoDB and demonstrated how to use it to find documents where a certain field is not equal to a specified value. We covered the syntax, example, explanation, use, and important points of the $ne
operator. The $ne
operator is a useful tool in MongoDB for querying certain documents and excluding others based on specific field values.