Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
-
$weekreturns the week number (0-53) of the year for a given date. -
$monthreturns the month number (1-12) for a given date. - Use
$projectstage to extract date components before grouping. - Combine with aggregation operators like
$avg,$sum, or$countfor 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.
Advertisements
