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 date records (ISODate format) in a range
To fetch date records within a specific range from MongoDB documents containing ISODate format dates, use range operators like $gte, $lte, $gt, and $lt in your queries, or aggregation pipeline operators for more complex date filtering.
Syntax
// Basic date range query
db.collection.find({
"dateField": {
"$gte": ISODate("start_date"),
"$lte": ISODate("end_date")
}
});
// Aggregation with time-based filtering
db.collection.aggregate([
{
"$redact": {
"$cond": {
"if": { "$and": [conditions] },
"then": "$$KEEP",
"else": "$$PRUNE"
}
}
}
]);
Sample Data
db.demo178.insertMany([
{"DueDate": new ISODate("2019-01-10T06:18:20.474Z")},
{"DueDate": new ISODate("2020-11-10T18:05:11.474Z")},
{"DueDate": new ISODate("2020-03-15T07:05:10.474Z")},
{"DueDate": new ISODate("2020-06-11T16:05:10.474Z")}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e397bd89e4f06af551997f5"),
ObjectId("5e397bf39e4f06af551997f6"),
ObjectId("5e397c039e4f06af551997f7"),
ObjectId("5e397c0f9e4f06af551997f8")
]
}
Display all documents from the collection ?
db.demo178.find();
{ "_id" : ObjectId("5e397bd89e4f06af551997f5"), "DueDate" : ISODate("2019-01-10T06:18:20.474Z") }
{ "_id" : ObjectId("5e397bf39e4f06af551997f6"), "DueDate" : ISODate("2020-11-10T18:05:11.474Z") }
{ "_id" : ObjectId("5e397c039e4f06af551997f7"), "DueDate" : ISODate("2020-03-15T07:05:10.474Z") }
{ "_id" : ObjectId("5e397c0f9e4f06af551997f8"), "DueDate" : ISODate("2020-06-11T16:05:10.474Z") }
Method 1: Hour Range Filtering
Filter documents where the hour of DueDate falls between 5 and 9 (6 AM to 8 AM) ?
db.demo178.aggregate([
{
"$redact": {
"$cond": {
"if": {
"$and": [
{ "$gt": [ {"$hour": "$DueDate"}, 5] },
{ "$lt": [ {"$hour": "$DueDate"}, 9] }
]
},
"then": "$$KEEP",
"else": "$$PRUNE"
}
}
}
]);
{ "_id" : ObjectId("5e397bd89e4f06af551997f5"), "DueDate" : ISODate("2019-01-10T06:18:20.474Z") }
{ "_id" : ObjectId("5e397c039e4f06af551997f7"), "DueDate" : ISODate("2020-03-15T07:05:10.474Z") }
Method 2: Date Range Query
Find documents with DueDate between January 2020 and July 2020 ?
db.demo178.find({
"DueDate": {
"$gte": ISODate("2020-01-01T00:00:00.000Z"),
"$lte": ISODate("2020-07-31T23:59:59.999Z")
}
});
{ "_id" : ObjectId("5e397c039e4f06af551997f7"), "DueDate" : ISODate("2020-03-15T07:05:10.474Z") }
{ "_id" : ObjectId("5e397c0f9e4f06af551997f8"), "DueDate" : ISODate("2020-06-11T16:05:10.474Z") }
Conclusion
Use $gte/$lte operators for basic date range queries and aggregation with $redact for complex time-based filtering. The $hour operator extracts hour values for time-specific comparisons within ISODate fields.
Advertisements
