Find the count of users who logged in between specific dates with MongoDB

To find the count of users who logged in between specific dates in MongoDB, use the count() method with $gte and $lt operators to define the date range filter.

Syntax

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

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")
    ]
}

Display 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") }

Count Users Between Specific Dates

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

Key Points

  • $gte includes the start date in the range
  • $lt excludes the end date from the range
  • Use new Date() or new ISODate() for date comparisons

Conclusion

The count() method with $gte and $lt operators efficiently counts documents within a specific date range. This approach returns only the count number, making it faster than using find().length() for large collections.

Updated on: 2026-03-15T01:15:39+05:30

400 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements