Jul 1, 2016

$not operator in MongoDB

$not returns the Boolean value to opposite of its expression, suppose expression evaluate the value false $not evaluate it true same as if expression evaluate true $not evaluate as false. $not operator treat as false to null, 0 and undefined.

Syntax:


{ $not: [ <expression> ] }


Example: Suppose we have a collection books. Write a query to select books which quantity is not less then 3.


{ "_id" : 1, "book_title" : "book1 ","price" : 20, "quantity" : 1, "date" : ISODate("2016-08-05T07:00:00Z") }
{ "_id" : 2, "book_title" : "book2", "price" : 10, "quantity" : 2, "date" : ISODate("2016-08-05T08:00:00Z") }
{ "_id" : 3, "book_title" : "book3", "price" : 30, "quantity" : 4, "date" : ISODate("2016-08-17T10:00:00Z") }
{ "_id" : 4, "book_title" : "book4", "price" : 10, "quantity" : 2, "date" : ISODate("2014-09-01T11:20:39.736Z") }
{ "_id" : 5, "book_title" : "book5", "price" : 20, "quantity" : 6, "date" : ISODate("2014-09-04T20:23:13.331Z") }


Query:


db.books.find({  
     "quantity":{$not:{"$lt":3}}
 })


Result:


{"_id" : 3,"book_title" : "book3","price" : 30,"quantity" : 4,"date" : ISODate("2016-08-17T10:00:00.000Z")}
{"_id" : 5,"book_title" : "book5","price" : 20,"quantity" : 6,"date" : ISODate("2014-09-04T20:23:13.331Z")}