Reputation: 127
I have some problems with data aggregation on mongoose. Would appreciate some help.
Here is my DB (minimized):
{
_id: 1,
timestamp: 2018-05-27T22:02:07.837+00:00,
},
{
_id: 2,
timestamp: 2019-10-27T22:02:07.837+00:00,
},
{
_id: 3,
timestamp: 2019-12-27T22:02:07.837+00:00,
},
{
_id: 4,
timestamp: 2020-01-27T22:02:07.837+00:00,
},
{
_id: 5,
timestamp: 2020-02-27T22:02:07.837+00:00,
},
{
_id: 6,
timestamp: 2020-09-27T22:02:07.837+00:00,
}
Here's the structure I'm aiming for:
[
[2018,5],
[2019,10],
[2019,12],
[2020,1],
[2020,2],
[2020,9]
]
currently my code is:
Model.aggregate([
{ $group: { _id: "$year", months: { $addToSet: "$month" } } }
]);
But I feel I'm quite far from what I try to achieve. Would appreciate some insights, thanks everyone!!
Upvotes: 0
Views: 693
Reputation: 127
After 5 hours I made it. Solution: https://mongoplayground.net/p/gFpFiK8vjkk
db.collection.aggregate([
{ $group: { _id: { year: { $year: "$timestamp" }, month: { $month: "$timestamp" } }, total: { $sum: 1 } } },
{ $sort: { "_id.year": -1, "_id.month": -1 } },
])
Upvotes: 1