mongo-db
  1. mongo-db-not-operator

$not Operator - (MongoDB Misc)

In MongoDB, the $not operator is a query operator that is used to negate the result of the expression or query condition. In this page, we will discuss how to use the $not operator in MongoDB.

Syntax

In MongoDB, the $not operator syntax is as follows:

{field: { $not: { <operator-expression> } } }

Example

Consider a collection named employees, which has the following documents:

{ "_id" : 1, "name" : "John", "age": 25 },
{ "_id" : 2, "name" : "Emma", "age": 35 },
{ "_id" : 3, "name" : "Mary", "age": 40 },
{ "_id" : 4, "name" : "Jessica", "age": 22 },
{ "_id" : 5, "name" : "Andrew", "age": 27 }

To find all employees whose age is not 25, you can use the $not operator as follows:

db.employees.find({ age: { $not: { $eq: 25 }}})

The above query will give the below output:

{ "_id" : 2, "name" : "Emma", "age": 35 },
{ "_id" : 3, "name" : "Mary", "age": 40 },
{ "_id" : 4, "name" : "Jessica", "age": 22 },
{ "_id" : 5, "name" : "Andrew", "age": 27 }

Explanation

The $not operator is used to negate the result of an expression or query condition. In the above example, the $not operator is used to find all employees whose age is not 25. The $eq operator is used to compare the age field with 25.

Use

The $not operator can be used to perform negation operation on an expression or query condition. It is useful when you want to specify a condition that is not covered by the other query operators.

Important Points

  • The $not operator negates the result of an expression or query condition.
  • The $not operator can be used with other query operators such as $eq, $in, and $regex.
  • The $not operator can be used to perform negation operation on a query condition.

Summary

In this page, we discussed the $not operator in MongoDB. We saw the syntax of the $not operator, an example of how to use it, its explanation, its use cases, and important points to keep in mind while using it. The $not operator is a useful operator to perform negation operation on an expression or query condition.

Published on: