$and Operator in MongoDB


$and operator is a Boolean operator in MongoDB, $and operator returns the value if it’s all expression evaluate true. It takes any number of expressions. This is the same as AND operator in a T-SQL query.

$and operator stop to evaluate the next expression if current returns are false. $and operator treat as false to null, 0 and undefined.
Syntax:

{ $and: [ <expression1>, <expression2>, ... ] }
Example: Suppose we have a collection of 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") }



Related Posts

What is the Use of isNaN Function in JavaScript? A Comprehensive Explanation for Effective Input Validation

In the world of JavaScript, input validation is a critical aspect of ensuring that user-provided data is processed correctly. One indispensa...