0

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.

2 Answers2

2

If you want to sort your query results in the descending order use:

$sort: {
"items.occurs": -1
}

See the docs $sort

h-sifat
  • 1,455
  • 3
  • 19
0

Following this question : mongodb sorting children of an array in a document [duplicate]

I try the suggestion of @kewne

And change on my pipeline:

$addToSet -> $push

And before the last $group I do:

$sort{
    "_id.customer_id" : 1, "count" : -1
}

So first sort all the data individually, then when I do the last $group the data is correctly ordered. This is the final 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
    },
}
}, {
$sort: {
    "_id.customer_id": 1,
    "count": -1
}
}, {
$group: {
    "_id": "$_id.customer_id",
    "items": {
        "$push": {
            "coverage_id": "$coverage_area_id",
            "occurs": "$count"
        }
    },
}
}]