Jul 1, 2016

$and Operator in MongoDB

$and operator is Boolean operator in mongodb, $and operator returns the value if it’s all expression evaluate true. Its take any number of expression. This is same like AND operator in T-SQL query.

$and operator stop to evaluation next expression if current returns false. $and operator treat as false to null, 0 and undefined.

Syntax:


{ $and: [ <expression1>, <expression2>, ... ] }


Example: Suppose we have a collection books. Write a query to select books which quantity =1 and price is 20.


{ "_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({  
     $and:[{"quantity":1},{"price":20}]
 })


Result:


{ "_id" : 1, "book_title" : "book1 ", "price" : 20, "quantity" : 1, "date" : ISODate("2016-08-05T07:00:00.000Z") }