Less than and Less than equals to query in MongoDB


To fetch records “less than” and “less than equals to” to specific value mongodb provide $lt and $lte operator respectively.

Syntax:


{ field: { $lt: value} } // for greater than
{ field: { $lte: value} } // for greater than equals to


Example: Suppose we have a collection “Order” now we want to fetch those documents which quantity is less than or less than equals to 4.


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


Query


db.Order.find({"qty":{$lt:4}}) // for less than
db.Order.find({"qty":{$lte:4}}) // for less than equals to


Results respectively


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



{ "_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" : 5, "item" : "item1", "qty" : 2, "Price" : 500 }


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