【问题标题】:MongoDB - Sum value in nested arrayMongoDB - 嵌套数组中的总和值
【发布时间】:2018-12-19 17:40:50
【问题描述】:

我有一个像这样的对象

{
    "_id" : {
        "import_type" : "MANUAL_UPLOAD",
        "supplier" : "jabino.de",
        "unit_price" : "0"
    },
    "statuses" : [ 
        {
            "status" : "DUPLICATED",
            "count" : 14
        }, 
        {
            "status" : "BLACKLISTED",
            "count" : 2
        }, 
        {
            "status" : "USABLE",
            "count" : 2239
        }, 
        {
            "status" : "INVALID_EMAIL_ADDRESS",
            "count" : 1
        }, 
        {
            "status" : "DUPLICATED",
            "count" : 14
        }, 
        {
            "status" : "BLACKLISTED",
            "count" : 2
        }, 
        {
            "status" : "USABLE",
            "count" : 2239
        }, 
        {
            "status" : "INVALID_EMAIL_ADDRESS",
            "count" : 1
        }
    ]
}

如何在statuses 数组中对具有相同status 的所有count 求和,而不会丢失_id 中的键值。例如。在这种情况下

  • 重复:28
  • 列入黑名单:4
  • 可用:4478
  • 电子邮件地址无效:2

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    您可以在下面使用aggregation

    db.collection.aggregate([
      { "$unwind": "$statuses" },
      { "$group": {
        "_id": {
          "_id": "$_id",
          "statuses": "$statuses.status"
        },
        "count": { "$sum": "$statuses.count" }
      }},
      { "$group": {
        "_id": "$_id._id",
        "statuses": {
          "$push": {
            "status": "$_id.statuses",
            "count": "$count"
          }
        }
      }}
    ])
    

    【讨论】:

    • 有效。非常感谢。
    • 2 分钟队友
    猜你喜欢
    • 2021-10-14
    • 2023-03-05
    • 1970-01-01
    • 2019-03-24
    • 2021-05-19
    • 1970-01-01
    • 2020-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多