0
0
MongoDBquery~5 mins

$gt and $gte for greater than in MongoDB

Choose your learning style9 modes available
Introduction

These operators help you find data where a value is bigger than a number. They make searching easier and faster.

Finding products with price greater than $50 in a store database.
Getting users older than 18 years in a user list.
Listing events happening after a certain date.
Finding books with more than 300 pages.
Filtering orders with quantity greater than or equal to 10.
Syntax
MongoDB
{ field: { $gt: value } }  // for greater than
{ field: { $gte: value } } // for greater than or equal to

$gt means 'greater than' and excludes the value itself.

$gte means 'greater than or equal to' and includes the value.

Examples
Finds documents where age is more than 18.
MongoDB
{ age: { $gt: 18 } }
Finds documents where price is 100 or more.
MongoDB
{ price: { $gte: 100 } }
Finds documents with score greater than 75.
MongoDB
{ score: { $gt: 75 } }
Sample Program

This example adds some products with prices. Then it finds products costing more than 20.

MongoDB
db.products.insertMany([
  { name: "Pen", price: 5 },
  { name: "Notebook", price: 15 },
  { name: "Backpack", price: 50 },
  { name: "Laptop", price: 1000 }
])

// Find products with price greater than 20
const expensiveProducts = db.products.find({ price: { $gt: 20 } }).toArray()

expensiveProducts
OutputSuccess
Important Notes

Remember $gt excludes the value itself, so price $20 won't show in the example above.

Use $gte if you want to include the value itself.

Summary

$gt finds values strictly greater than a number.

$gte finds values greater than or equal to a number.

They help filter data easily in MongoDB queries.