$and operator in MongoDB


$and: This operator works the same as AND in SQL Server. $and operator uses to perform a logical operation on two or more than two arrays and select the documents that satisfy all expression.

Syntax:


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


Example: Suppose we have a collection “Order” and want to select those records whose quantity is 2 and the price is 200. See the following collection.


{ "_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 }


Run the following query to get the expected result described above.


db.Order.find({$and:[{qty:2},{Price:200}]})


Result:


{ "_id" : 2, "item" : "item1", "qty" : 2, "Price" : 200 }

No comments:

Post a Comment

Please do not enter any spam link in the comment box.

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...