Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Searching for ranges in MongoDB?
To search for ranges in MongoDB, use comparison operators like $gte, $lte, $gt, and $lt to find documents within specific value ranges. You can combine these with sort() and limit() for more control over results.
Syntax
db.collection.find({
field: { $gte: minValue, $lte: maxValue }
});
Sample Data
db.demo665.insertMany([
{ "Value": 10 },
{ "Value": 15 },
{ "Value": 55 },
{ "Value": 25 },
{ "Value": 20 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ea1bf1424113ea5458c7d08"),
ObjectId("5ea1bf1b24113ea5458c7d09"),
ObjectId("5ea1bf1e24113ea5458c7d0a"),
ObjectId("5ea1bf2324113ea5458c7d0b"),
ObjectId("5ea1bf2b24113ea5458c7d0c")
]
}
Display all documents from the collection −
db.demo665.find();
{ "_id": ObjectId("5ea1bf1424113ea5458c7d08"), "Value": 10 }
{ "_id": ObjectId("5ea1bf1b24113ea5458c7d09"), "Value": 15 }
{ "_id": ObjectId("5ea1bf1e24113ea5458c7d0a"), "Value": 55 }
{ "_id": ObjectId("5ea1bf2324113ea5458c7d0b"), "Value": 25 }
{ "_id": ObjectId("5ea1bf2b24113ea5458c7d0c"), "Value": 20 }
Example: Range Search with Sort and Limit
Find values ? 30, sort in descending order, and limit to top 2 results −
db.demo665.find({ Value: { $lte: 30 } }).sort({ Value: -1 }).limit(2);
{ "_id": ObjectId("5ea1bf2324113ea5458c7d0b"), "Value": 25 }
{ "_id": ObjectId("5ea1bf2b24113ea5458c7d0c"), "Value": 20 }
Date Range Operators
-
$gte− Greater than or equal to -
$lte− Less than or equal to -
$gt− Greater than -
$lt− Less than
Conclusion
Use MongoDB range operators like $gte and $lte to query documents within specific value ranges. Combine with sort() and limit() to control result ordering and quantity.
Advertisements
