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
Find objects between two dates in MongoDB?
Use the $gte (greater than or equal) and $lt (less than) operators with ISODate() to find documents between two dates in MongoDB.
Create Sample Data
db.order.insertMany([
{"OrderId": 1, "OrderAddress": "US", "OrderDateTime": ISODate("2019-02-19")},
{"OrderId": 2, "OrderAddress": "UK", "OrderDateTime": ISODate("2019-02-26")},
{"OrderId": 3, "OrderAddress": "IN", "OrderDateTime": ISODate("2019-03-05")}
]);
Find Between Two Dates
Find orders between Feb 10 and Feb 21 ?
db.order.find({
"OrderDateTime": {
$gte: ISODate("2019-02-10"),
$lt: ISODate("2019-02-21")
}
}).pretty();
{
"_id": ObjectId("..."),
"OrderId": 1,
"OrderAddress": "US",
"OrderDateTime": ISODate("2019-02-19T00:00:00Z")
}
Only OrderId 1 (Feb 19) is returned because it falls within the range. OrderId 2 (Feb 26) is excluded by $lt.
Date Range Operators
| Operator | Meaning | Includes Boundary? |
|---|---|---|
$gte |
Greater than or equal | Yes (start date included) |
$gt |
Greater than | No (start date excluded) |
$lte |
Less than or equal | Yes (end date included) |
$lt |
Less than | No (end date excluded) |
Use $gte + $lte to include both boundaries, or $gte + $lt to exclude the end date.
Conclusion
Combine $gte and $lt (or $lte) with ISODate() to query documents within a date range in MongoDB. Ensure date fields are stored as ISODate objects for accurate comparisons.
Advertisements
