Find data for specific date in MongoDB?

To find data for a specific date in MongoDB, use the $gte and $lt operators to create a date range. These operators help filter documents where the date field falls within the specified range.

Syntax

db.collection.find({
    "dateField": {
        "$gte": new Date("YYYY-MM-DD"),
        "$lt": new Date("YYYY-MM-DD")
    }
});

Sample Data

db.findDataByDateDemo.insertMany([
    { "UserName": "John", "UserLoginDate": new ISODate("2019-01-31") },
    { "UserName": "Larry", "UserLoginDate": new ISODate("2019-02-01") },
    { "UserName": "Sam", "UserLoginDate": new ISODate("2019-05-02") },
    { "UserName": "David", "UserLoginDate": new ISODate("2019-05-16") },
    { "UserName": "Carol", "UserLoginDate": new ISODate("2019-10-19") }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cdd8cd7bf3115999ed511ed"),
        ObjectId("5cdd8ce7bf3115999ed511ee"),
        ObjectId("5cdd8cf3bf3115999ed511ef"),
        ObjectId("5cdd8d00bf3115999ed511f0"),
        ObjectId("5cdd8d0ebf3115999ed511f1")
    ]
}

View All Documents

db.findDataByDateDemo.find();
{ "_id": ObjectId("5cdd8cd7bf3115999ed511ed"), "UserName": "John", "UserLoginDate": ISODate("2019-01-31T00:00:00Z") }
{ "_id": ObjectId("5cdd8ce7bf3115999ed511ee"), "UserName": "Larry", "UserLoginDate": ISODate("2019-02-01T00:00:00Z") }
{ "_id": ObjectId("5cdd8cf3bf3115999ed511ef"), "UserName": "Sam", "UserLoginDate": ISODate("2019-05-02T00:00:00Z") }
{ "_id": ObjectId("5cdd8d00bf3115999ed511f0"), "UserName": "David", "UserLoginDate": ISODate("2019-05-16T00:00:00Z") }
{ "_id": ObjectId("5cdd8d0ebf3115999ed511f1"), "UserName": "Carol", "UserLoginDate": ISODate("2019-10-19T00:00:00Z") }

Example: Count Users by Date Range

Count users who logged in between May 2, 2019 and May 18, 2019 ?

db.findDataByDateDemo.count({
    "UserLoginDate": {
        "$gte": new Date("2019-05-02"),
        "$lt": new Date("2019-05-18")
    }
});
2

Find Documents by Date Range

Retrieve the actual documents instead of just counting them ?

db.findDataByDateDemo.find({
    "UserLoginDate": {
        "$gte": new Date("2019-05-02"),
        "$lt": new Date("2019-05-18")
    }
});
{ "_id": ObjectId("5cdd8cf3bf3115999ed511ef"), "UserName": "Sam", "UserLoginDate": ISODate("2019-05-02T00:00:00Z") }
{ "_id": ObjectId("5cdd8d00bf3115999ed511f0"), "UserName": "David", "UserLoginDate": ISODate("2019-05-16T00:00:00Z") }

Key Points

  • $gte includes the start date (greater than or equal)
  • $lt excludes the end date (less than)
  • Use ISODate() for precise date storage and new Date() for queries

Conclusion

Use $gte and $lt operators to create date ranges for filtering MongoDB documents. This approach efficiently finds documents within specific date periods while maintaining proper date boundary handling.

Updated on: 2026-03-15T01:25:09+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements