I have a list of Orders and I need to group them and know occurrences of orders by zones, that's why a do a $group and create a variable count by a $sum
This is my pipeline:
[{
$match: {
"status": "delivered",
"created_at": {
$lte: ISODate("2021-12-31T01:11:11.000Z")
},
"created_at": {
$gte: ISODate("2021-01-01T01:11:11.000Z")
},
"type": "delivery",
}
}, {
$project: {
"customer_id": 1,
"coverage_area_id": "$address.coverage_id",
}
}, {
$group: {
"_id": {
"customer_id": "$customer_id",
"coverage": "$coverage_area_id"
},
"coverage_area_id": {
$first: "$coverage_area_id"
},
"count": {
$sum: 1
},
}
}, {
$group: {
"_id": "$_id.customer_id",
"items": {
"$addToSet": {
"coverage_id": "$coverage_area_id",
"occurs": "$count",
}
},
}
}, {
$sort: {
"items.occurs": 1
}
}]
And this is a result output:
_id:"f487a0eaa67da18"
items:Array
0:Object
coverage_id: ObjectId("784c5718cf0d72")
occurs:4
1:Object
coverage_id: ObjectId("317922f03c8c70")
occurs:3
2:Object
coverage_id: ObjectId("317922f03c8c65")
occurs:2
3:Object
coverage_id: ObjectId("15cfab3866a811")
occurs:1
4:Object
coverage_id: ObjectId("1ff92c160a12d3")
occurs:9
I need than the result of occurs:9 be sorted as the first value but I don't see clearly why this is not happening.