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
Group by dates in MongoDB?
You can use the aggregate framework to group by dates in MongoDB. The aggregation pipeline provides powerful date operators to group documents by specific date components like day, month, or year.
Sample Data
Let us first create a collection with some documents containing date fields ?
db.groupByDateDemo.insertMany([
{"UserLoginDateTime": new ISODate()},
{"UserLoginDateTime": new ISODate("2019-01-31T15:20:09.234Z")},
{"UserLoginDateTime": new ISODate("2017-04-21T16:12:13.240Z")},
{"UserLoginDateTime": new ISODate("2016-05-25T19:11:21.130Z")},
{"UserLoginDateTime": new ISODate("2016-05-25T19:11:21.130Z")},
{"UserLoginDateTime": new ISODate()}
]);
Display all documents from the collection using the find() method ?
db.groupByDateDemo.find().pretty();
{
"_id" : ObjectId("5c6ee4df6fd07954a4890695"),
"UserLoginDateTime" : ISODate("2019-02-21T17:50:23.076Z")
}
{
"_id" : ObjectId("5c6ee51c6fd07954a4890696"),
"UserLoginDateTime" : ISODate("2019-01-31T15:20:09.234Z")
}
{
"_id" : ObjectId("5c6ee5336fd07954a4890697"),
"UserLoginDateTime" : ISODate("2017-04-21T16:12:13.240Z")
}
{
"_id" : ObjectId("5c6ee54b6fd07954a4890698"),
"UserLoginDateTime" : ISODate("2016-05-25T19:11:21.130Z")
}
{
"_id" : ObjectId("5c6ee8de6fd07954a4890699"),
"UserLoginDateTime" : ISODate("2016-05-25T19:11:21.130Z")
}
{
"_id" : ObjectId("5c6ee8e76fd07954a489069a"),
"UserLoginDateTime" : ISODate("2019-02-21T18:07:35.208Z")
}
Group by Dates Using Aggregation
Here is the query to group by dates in MongoDB using the aggregation pipeline ?
db.groupByDateDemo.aggregate([
{
$group: {
_id: {
$add: [
{ $dayOfYear: "$UserLoginDateTime"},
{ $multiply: [400, {$year: "$UserLoginDateTime"}] }
]
},
NumberOfTimes: { $sum: 1 },
f: {$min: "$UserLoginDateTime"}
}
},
{ $sort: {_id: 1} },
{ $limit: 10 },
{ $project: { date: "$f", NumberOfTimes: 1, _id: 0} }
]);
{ "NumberOfTimes" : 2, "date" : ISODate("2016-05-25T19:11:21.130Z") }
{ "NumberOfTimes" : 1, "date" : ISODate("2017-04-21T16:12:13.240Z") }
{ "NumberOfTimes" : 1, "date" : ISODate("2019-01-31T15:20:09.234Z") }
{ "NumberOfTimes" : 2, "date" : ISODate("2019-02-21T17:50:23.076Z") }
How It Works
The aggregation pipeline uses several date operators:
-
$dayOfYearextracts the day number within the year (1-366) -
$yearextracts the year component from the date -
$multiplyand$addcreate a unique identifier for each date -
$sum: 1counts occurrences for each grouped date -
$minselects the earliest timestamp for that date
Conclusion
MongoDB's aggregation framework provides powerful date grouping capabilities using operators like $dayOfYear and $year. This approach effectively counts document occurrences per date and can be extended for monthly or yearly grouping patterns.
