MongoDB query to get date records in a range

To get date records in a range, use the $gt (greater than) and $lt (less than) operators together to define the date boundaries for your query.

Syntax

db.collection.find({
    "dateField": {
        "$gt": ISODate("start-date"),
        "$lt": ISODate("end-date")
    }
});

Sample Data

db.demo60.insertMany([
    {"ArrivalDate": new ISODate("2019-01-11 12:30:10")},
    {"ArrivalDate": new ISODate("2019-10-12 03:10:00")},
    {"ArrivalDate": new ISODate("2019-01-14 05:11:20")}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e2863fecfb11e5c34d89927"),
        ObjectId("5e28641acfb11e5c34d89928"),
        ObjectId("5e28642acfb11e5c34d89929")
    ]
}

Display all documents from the collection ?

db.demo60.find();
{ "_id": ObjectId("5e2863fecfb11e5c34d89927"), "ArrivalDate": ISODate("2019-01-11T12:30:10Z") }
{ "_id": ObjectId("5e28641acfb11e5c34d89928"), "ArrivalDate": ISODate("2019-10-12T03:10:00Z") }
{ "_id": ObjectId("5e28642acfb11e5c34d89929"), "ArrivalDate": ISODate("2019-01-14T05:11:20Z") }

Example: Query Date Range

Find documents with ArrivalDate between January 9, 2019 and January 16, 2019 ?

db.demo60.find({
    "ArrivalDate": {
        "$gt": ISODate("2019-01-09T12:30:10Z"),
        "$lt": ISODate("2019-01-16T12:30:10Z")
    }
});
{ "_id": ObjectId("5e2863fecfb11e5c34d89927"), "ArrivalDate": ISODate("2019-01-11T12:30:10Z") }
{ "_id": ObjectId("5e28642acfb11e5c34d89929"), "ArrivalDate": ISODate("2019-01-14T05:11:20Z") }

Date Range Operators

  • $gt − Greater than (exclusive)
  • $gte − Greater than or equal (inclusive)
  • $lt − Less than (exclusive)
  • $lte − Less than or equal (inclusive)

Conclusion

Use $gt and $lt operators together to query date records within a specific range. The query returns documents where the date field falls between the specified start and end dates.

Updated on: 2026-03-15T02:51:38+05:30

436 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements