I'm struggling with something which is most likely very stupid on my behalf.
I have a data set in a mongo collection and I wanted to get all the sum of documents grouped by year and month (which I can do fine). However I then want to have those results ordered by year and month.
Here is my query for getting the results with just the sum:
db.xxxx.aggregate([
{
$group: {
_id: { year:
{ $year: "$createdDate" },
month: { $month: "$createdDate" }
},
total_users: { $sum: 1 }
},
}
])
Which results in this:
[
{ _id: { year: 2021, month: 12 }, total_users: 191 },
{ _id: { year: 2021, month: 6 }, total_users: 51 },
{ _id: { year: 2022, month: 3 }, total_users: 165 },
{ _id: { year: 2022, month: 8 }, total_users: 61 },
{ _id: { year: 2021, month: 8 }, total_users: 182 },
{ _id: { year: 2021, month: 11 }, total_users: 81 },
{ _id: { year: 2022, month: 4 }, total_users: 155 },
{ _id: { year: 2022, month: 7 }, total_users: 10 },
{ _id: { year: 2022, month: 5 }, total_users: 31 },
{ _id: { year: 2022, month: 9 }, total_users: 23 },
{ _id: { year: 2021, month: 7 }, total_users: 48 },
{ _id: { year: 2021, month: 10 }, total_users: 75 },
{ _id: { year: 2021, month: 5 }, total_users: 11 },
{ _id: { year: 2022, month: 2 }, total_users: 300 },
{ _id: { year: 2021, month: 9 }, total_users: 131 },
{ _id: { year: 2022, month: 1 }, total_users: 172 },
{ _id: { year: 2022, month: 6 }, total_users: 65 }
]
Now once I try and sort by month and year I get a token error:
db.xxxx.aggregate([
{
$group: {
_id: { year:
{ $year: "$createdDate" },
month: { $month: "$createdDate" }
},
total_users: { $sum: 1 }
},
{$sort: {year:1}},
{$sort: {month:1}}
}
])
Resulting error:
Uncaught:
SyntaxError: Unexpected token (10:4)
8 | total_users: { $sum: 1 }
9 | },
> 10 | {$sort: {year:1}},
| ^
11 |
Atlas [primary] collection> {$sort: {month:1}}
1
Atlas [primary] collection> }
Uncaught:
SyntaxError: Unexpected token (1:0)
> 1 | }
| ^
2 |
Any help would be very welcome!!
Thanks
EDIT
Here's the query now the suggested sort query:
db.xxx.aggregate([
{
$group: {
_id: { year:
{ $year: "$createdDate" },
month: { $month: "$createdDate" }
},
total_users: { $sum: 1 }
},
{
$sort: {
"_id.year": 1,
"_id.month": 1
}
}
}
])
Note I'm still getting the same error
CodePudding user response:
You want to use:
{$sort: {"_id.year": 1, "_id.month": 1}}
See how it works on the playground example
EDIT:
You have misplayed the }
. The $group
is missing one at the end and the $sort
have extra one. It should be:
db.collection.aggregate([
{$group: {
_id: {year: {$year: "$createdDate"}, month: {$month: "$createdDate"}},
total_users: {$sum: 1}
}
},
{$sort: {"_id.year": 1, "_id.month": 1}}
])