Before explaining $not operator I want to remind you about NOT IN in SQL Server. In T-SQL query we used NOT operator like below.
<SELECT QUERY> <WHERE ID> NOT IN (<a sub query>)
Same like this $not operator behave in mongodb.
$not performs a logical NOT operation on the specified <operator-expression> and selects the documents that do not match the <operator-expression>. This includes documents that do not contain the field.
Syntax:
Syntax: { field: { $not: { <operator-expression> } } } |
Example: Suppose we have a collection of books inventory like below.
{ "_id" : 1, "item" : "item1", "qty" : 1, "Price" : 500 } { "_id" : 2, "item" : "item1", "qty" : 2, "Price" : 200 } { "_id" : 3, "item" : "item1", "qty" : 4, "Price" : 300 } { "_id" : 4, "item" : "item1", "qty" : 8, "Price" : 700 } { "_id" : 5, "item" : "item1", "qty" : 2, "Price" : 500 } |
See following query
db.Order.find( { qty: { $not: { $gte: 4 } } } ) |
Result:
{ "_id" : 1, "item" : "item1", "qty" : 1, "Price" : 500 } { "_id" : 2, "item" : "item1", "qty" : 2, "Price" : 200 } { "_id" : 5, "item" : "item1", "qty" : 2, "Price" : 500 } |
Note:
- The operation of the $not operator is consistent with the behavior of other operators but may yield unexpected results with some data types like arrays.
- The $not operator does not support operations with the $regex operator. Instead use // or in your driver interfaces, use your language’s regular expression capability to create regular expression objects.
For more details you can follow this link https://docs.mongodb.com/manual/reference/operator/query/not/