Reputation: 6019
This Meteor server code tries to group documents and sort them by the property "period" ascending but it is not doing it, any idea how to fix it? thx
let invoicePopulation = UsageCol.aggregate([
{
$match: {
action: {$in: ['a', 'b', 'c']},
userId: doc.userId
}
},
{
$group: {
_id: {period: "$period"},
count: {$sum: 1}
}
},
{
"$sort" : {
"period" : 1
}
}
]);
//output
[{"_id":{"period":"42017"},"count":14},{"_id":{"period":"22017"},"count":1},{"_id":{"period":"32017"},"count":271}]
//needs to be
[{"_id":{"period":"22017"},"count":1},{"_id":{"period":"32017"},"count":271},{"_id":{"period":"42017"},"count":14}]
Upvotes: 0
Views: 70
Reputation: 10705
Your $group
looks strange to me. Typically you want to group on a specific field and that field would become your _id
(since the field is now unique).
The way you have it in your code is setting a sub document as the value for _id
. If that is truly what you want, then your $sort
should be this.
{
$sort: {
"_id.period": 1
}
}
If you are not trying to create an _id
sub-document, then you should fix your $group
like this.
let invoicePopulation = UsageCol.aggregate([
{
$match: {
action: {$in: ['a', 'b', 'c']},
userId: doc.userId
}
},
{
$group: {
_id: "$period",
count: {$sum: 1}
}
},
{
$sort : {
"period" : 1
}
}
]);
Upvotes: 1