How to search date between two dates in MongoDB?

To search date between two dates in MongoDB, use $gte and $lt operators. The $gte operator matches dates greater than or equal to the start date, while $lt matches dates less than the end date.

Syntax

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

Sample Data

Let us create a collection with documents ?

db.demo524.insertMany([
    {"EndDate": new ISODate("2020-01-19")},
    {"EndDate": new ISODate("2020-01-20")},
    {"EndDate": new ISODate("2020-12-31")}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e8adbe5437efc8605595b63"),
        ObjectId("5e8adbec437efc8605595b64"),
        ObjectId("5e8adbf3437efc8605595b65")
    ]
}

Display all documents from the collection ?

db.demo524.find();
{ "_id": ObjectId("5e8adbe5437efc8605595b63"), "EndDate": ISODate("2020-01-19T00:00:00Z") }
{ "_id": ObjectId("5e8adbec437efc8605595b64"), "EndDate": ISODate("2020-01-20T00:00:00Z") }
{ "_id": ObjectId("5e8adbf3437efc8605595b65"), "EndDate": ISODate("2020-12-31T00:00:00Z") }

Example

Search for documents with EndDate between January 4, 2020 and January 31, 2020 ?

var first = new ISODate("2020-01-04");
var last = new ISODate("2020-01-31");
db.demo524.find({EndDate: {$gte: first, $lt: last}});
{ "_id": ObjectId("5e8adbe5437efc8605595b63"), "EndDate": ISODate("2020-01-19T00:00:00Z") }
{ "_id": ObjectId("5e8adbec437efc8605595b64"), "EndDate": ISODate("2020-01-20T00:00:00Z") }

Date Range Operators

  • $gte - Greater than or equal to (includes start date)
  • $lt - Less than (excludes end date)
  • $lte - Less than or equal to (includes end date)
  • $gt - Greater than (excludes start date)

Conclusion

Use $gte and $lt operators together to query documents with dates falling within a specific range. This combination includes the start date but excludes the end date from the results.

Updated on: 2026-03-15T03:23:06+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements