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
MongoDB query to fetch elements between a range excluding both the numbers used to set range?
To fetch elements between a range in MongoDB while excluding both boundary numbers, use the $gt (greater than) and $lt (less than) operators together in your query.
Syntax
db.collectionName.find({
fieldName: { $gt: lowerBound, $lt: upperBound }
});
For including both boundary numbers, use $gte and $lte operators ?
db.collectionName.find({
fieldName: { $gte: lowerBound, $lte: upperBound }
});
Sample Data
db.returnEverythingBetween50And60.insertMany([
{"Amount": 55},
{"Amount": 45},
{"Amount": 50},
{"Amount": 59},
{"Amount": 60},
{"Amount": 49},
{"Amount": 71}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd3c42eedc6604c74817cdb"),
ObjectId("5cd3c432edc6604c74817cdc"),
ObjectId("5cd3c436edc6604c74817cdd"),
ObjectId("5cd3c43aedc6604c74817cde"),
ObjectId("5cd3c43eedc6604c74817cdf"),
ObjectId("5cd3c442edc6604c74817ce0"),
ObjectId("5cd3c445edc6604c74817ce1")
]
}
Display all documents to verify our data ?
db.returnEverythingBetween50And60.find().pretty();
{ "_id": ObjectId("5cd3c42eedc6604c74817cdb"), "Amount": 55 }
{ "_id": ObjectId("5cd3c432edc6604c74817cdc"), "Amount": 45 }
{ "_id": ObjectId("5cd3c436edc6604c74817cdd"), "Amount": 50 }
{ "_id": ObjectId("5cd3c43aedc6604c74817cde"), "Amount": 59 }
{ "_id": ObjectId("5cd3c43eedc6604c74817cdf"), "Amount": 60 }
{ "_id": ObjectId("5cd3c442edc6604c74817ce0"), "Amount": 49 }
{ "_id": ObjectId("5cd3c445edc6604c74817ce1"), "Amount": 71 }
Example: Range Query Excluding Boundaries
Find all documents with Amount between 50 and 60, excluding 50 and 60 ?
db.returnEverythingBetween50And60.find({
Amount: { $gt: 50, $lt: 60 }
});
{ "_id": ObjectId("5cd3c42eedc6604c74817cdb"), "Amount": 55 }
{ "_id": ObjectId("5cd3c43aedc6604c74817cde"), "Amount": 59 }
Key Points
-
$gtand$ltcreate an exclusive range (boundary values excluded) -
$gteand$ltecreate an inclusive range (boundary values included) - Both operators can be combined in the same query for precise range filtering
Conclusion
Use $gt and $lt operators together to query elements within a range while excluding both boundary numbers. This provides precise control over range-based filtering in MongoDB collections.
Advertisements
