$or Operator in MongoDB

$or operator returns the value of one expression true from it’s all expression. Its takes any number of expression. $or operator same as like OR operator in SQL Server.

$or operator stops the evaluation if it finds expression true for it’s all expression. $or operator treat as true to null, 0 and undefined.

Syntax:


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


Example: Suppose we have a collection book. Write a query to select books in which quantity =1 or 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({  
     $or:[{"quantity":1},{"price":20}]
 })


Result:


{ "_id" : 1, "book_title" : "book1 ", "price" : 20, "quantity" : 1, "date" : ISODate("2016-08-05T07:00:00.000Z") }
{ "_id" : 5, "book_title" : "book5", "price" : 20, "quantity" : 6, "date" : ISODate("2014-09-04T20:23:13.331Z") }



No comments:

Post a Comment

PostgreSQL: How to change the password of the user

This article will teach you to change the password of the user in PostgreSQL. To change the password, we use the ALTER ROLE, its uses are ...