计算文档及其数组的总和 属性,按子文档的多个属性分组

Count documents and total sum of their array property, grouped by multiple properties of a subdocument

有 N 个以下类型的文档:

{
    "source": {
        "domain": "1",
        "type": "2"
    },
    "assets": [1, 2]
}
{
    "source": {
        "domain": "3",
        "type": "4"
    },
    "assets": [3, 4, 5]
}

如何获得所有文档中资产的总数,按域 + 类型分组?

在上述情况下,查询应该 return domain:1 + type:2 在 1 个文档中有 2 个组合资产,而 domain3 + type:4 有 3 个组合资产在 1 个文档中。

请注意 domain:1 + type:2 != domain:2 + type:1

我的第一次尝试是

collection.aggregate([
    {
        "$project": {
            "_id": 0,
            "arraySize":{"$size":"$assets"}
        }
    },
    {
        "$group": {
        "_id": {"$concat": ["$source.domain", "-", "$source.type"]},
        "totalArraysSize":{"$sum":"$arraySize"}
        }
    },
])

但只有 return 秒 [{'_id': None, 'totalArraysSize': 616}],没有分组。

我在尝试语法后设法编写了一个解决方案:

collection.aggregate([{
    "$group": {
        "_id": {"source": "$source.domain", "type": "$source.type"},
        "asset_count":{"$sum":{"$size":"$assets"}},
        "total_count":{"$sum": 1},
    }
}])