【问题标题】:Count documents and total sum of their array property, grouped by multiple properties of a subdocument计数文档及其数组属性的总和,按子文档的多个属性分组
【发布时间】:2022-01-06 11:03:10
【问题描述】:

拥有以下类型的 N 个文档:

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

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

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

注意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"}
        }
    },
])

但它只返回[{'_id': None, 'totalArraysSize': 616}],没有分组。

【问题讨论】:

    标签: python mongodb pymongo


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 2017-07-26
      • 2016-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多