$or operator in MongoDB

$or: If you are aware with SQL Server, $or operator behaves the same as OR in SQL Server. $or operator uses to perform logical OR operation on two or more than two arrays and its select the documents that satisfy at least one of the expression.

Syntax:


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


Example: Suppose we have a collection “Order” and want to select those records whose quantity is 1or 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 exact result described above.


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


Result:



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

No comments:

Post a Comment

PostgreSQL-Query: Sort result set by specific field values using ORDER BY Clause

Problem: Suppose we have a book_inventory table which has some columns such as id, isbn, title, author, publisher, publish_date, etc.. whe...