Less than and greater than in MongoDB

$lt and $gt are the two commands used to get the values greater than given value and less than given value, it is same as between in sql server.

$lte and $gte will used as 'less than or equal to' and 'greater than or equal to'

Better to use $lt and $gt in the given find statement to get the exact records, because Mongodb allows users to pass the different data types for the same field, giving both $lt and $gt will give the actual and expected output.

Let the initial data in the database be:

{ "pname" : "Apple",  "Price" : 600,  "Location" : "US"  }
{ "pname" : "Microsoft",  "Price" : 400,  "Location" : "UK"  }
{ "pname" : "Motorolla",  "Price" : 250,  "Location" : "India"  }
{ "pname" : "lenevo",  "Price" : 230,  "Location" : "Argentina"  }
{ "pname" : "MI",  "Price" : 290,  "Location" : "Chile"  }
{ "pname" : "samsung",  "Price" : 320,  "Location" : "Singapore"  }


Using $lt and $gt for integer values

db.products.find({Price:{$gt:350}})

db.products.find({Price:{$lt:250}})

First statement will return the documents with Price greater than 350 and Second statement will return the documents of Price less than 250

Using $lte and $gte for string values

db.products.find({pname:{$gte:'h'}})

db.products.find({pname:{$lte:'D'}})

First statement will return the documents with pname ‘h’ and alphabetically greater than 'h'  and Second statement will return the documents of pname with ‘D’ and alphabetically less than 'D'

Using $lt and $gt together

db.products.find({Price:{$gt:290,$lt:400}})

The above Query will return the documents of price greater than 290 and less than 400

{ "pname" : "samsung", "Price" : 320, "Location" : "Singapore" }