Group by day/month/week based on the date range in MongoDB

To group documents by day, week, or month based on date ranges in MongoDB, use the $group stage with date operators like $week, $month, and $dayOfMonth in an aggregation pipeline.

Syntax

db.collection.aggregate([
    {
        $project: {
            dateField: 1,
            week: { $week: "$dateField" },
            month: { $month: "$dateField" },
            day: { $dayOfMonth: "$dateField" }
        }
    },
    {
        $group: {
            _id: "$week", // or "$month" or "$day"
            // aggregation operations
        }
    }
]);

Sample Data

db.demo133.insertMany([
    {"Rank": 18, "DueDate": new ISODate("2020-01-10")},
    {"Rank": 12, "DueDate": new ISODate("2020-01-10")},
    {"Rank": 12, "DueDate": new ISODate("2020-02-01")},
    {"Rank": 20, "DueDate": new ISODate("2020-02-01")}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("..."),
        ObjectId("..."),
        ObjectId("..."),
        ObjectId("...")
    ]
}

View Sample Data

db.demo133.find();
{ "_id": ObjectId("..."), "Rank": 18, "DueDate": ISODate("2020-01-10T00:00:00Z") }
{ "_id": ObjectId("..."), "Rank": 12, "DueDate": ISODate("2020-01-10T00:00:00Z") }
{ "_id": ObjectId("..."), "Rank": 12, "DueDate": ISODate("2020-02-01T00:00:00Z") }
{ "_id": ObjectId("..."), "Rank": 20, "DueDate": ISODate("2020-02-01T00:00:00Z") }

Example: Group by Week with Average Calculation

db.demo133.aggregate([
    {
        "$project": {
            "DueDateWeek": { "$week": "$DueDate" },
            "DueDateMonth": { "$month": "$DueDate" },
            "Rank": 1
        }
    },
    {
        "$group": {
            "_id": "$DueDateWeek",
            "AvgValue": { "$avg": "$Rank" },
            "MonthValue": { "$first": "$DueDateMonth" }
        }
    }
]);
{ "_id": 4, "AvgValue": 16, "MonthValue": 2 }
{ "_id": 1, "AvgValue": 15, "MonthValue": 1 }

Key Points

  • $week returns the week number (0-53) of the year for a given date.
  • $month returns the month number (1-12) for a given date.
  • Use $project stage to extract date components before grouping.
  • Combine with aggregation operators like $avg, $sum, or $count for calculations.

Conclusion

MongoDB's date operators like $week and $month enable efficient grouping by time periods. Use $project to extract date components, then $group to aggregate data within those periods.

Updated on: 2026-03-15T02:12:54+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements