【问题标题】:Group By Unique Values and get Total for Each按唯一值分组并获得每个值的总计
【发布时间】:2020-03-30 09:02:51
【问题描述】:

我正在尝试计算文档中特定值的出现次数。我的文档结构如下:

  id: ObjectID("ABC123")
StoreItems: Array
    0: Object
        Type: "Apple"
        Color: "Green"
        Size: "Small"
        Weight: "5"
    1: Object
        Type: "Orange"
        Color: "Orange"
        Size: "Small"
        Weight: "8"
    2: Object
        Type: "Grapes"
        Color: "Green"
        Size: "Small"
        Weight: "8"

当我使用以下内容时,它只给我分组的总数,而不是每个特定类型:

[
    {
        '$unwind': {
            'path': '$StoreItems'
        }
    }, {
        '$match': {
            'StoreItems.Color': 'Green'
        }
    }, {
        '$group': {
            '_id': 'Type', 
            'Count': {
                '$sum': 1
            }
        }
    }
]

我想得到一个结果:Apples: 1, Grapes:3

但是,我只得到一个结果:Type: 4

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您应该更改构建_id for $group 语句的方式。目前它是一个静态值Type,而您需要引用StoreItems.Type(以美元开头):

    {
        '$group': {
            '_id': '$StoreItems.Type', 
            'Count': {
                '$sum': 1
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-18
      • 2021-10-09
      • 2020-07-15
      • 2012-04-08
      • 2015-01-26
      • 2020-02-10
      • 2020-10-06
      • 1970-01-01
      相关资源
      最近更新 更多