Jul 20, 2016

Greater than and greater than equal to query in MongoDB

To fetch records “greater than” and “greater than equals to” to a specific value, mongodb provide $gt and $gte operator respectively.

Syntax:


--For greater than
{field: {$gt: value} }
--For greater than equals to
{field: {$gte: value} }


Example: Suppose we have a collection “Order” now we want to fetch those documents which quantity is greater than 2.


{ "_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 following queries


db.Order.find({"qty":{$gt:2}})   // for greater than
db.Order.find({"qty":{$gte:2}})  // for greater than equals to


Results respectively


{ "_id" : 3, "item" : "item1", "qty" : 4, "Price" : 300 }
{ "_id" : 4, "item" : "item1", "qty" : 8, "Price" : 700 }



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