【问题标题】:Mongodb - group by value and get countMongodb - 按值分组并获取计数
【发布时间】:2020-03-12 04:18:00
【问题描述】:

我有一个聚合查询,它返回类似

的结果
    {
      count:1,
      status: 'FAILED',
      article_id: 1
    },
    {
      count:1,
      status: 'DELIVERED',
      article_id: 1
    }

我想按 article_id 分组并根据状态获取计数,如下所示:

   {
      article_id:1,
      FAILED:1,
      DELIVERED:2
   }

我该如何存档? 提前致谢。

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    其他答案原则上可能有效,但是它们被硬编码为状态FAILEDDELIVERED

    如果您想对任意状态有一个通用的解决方案,您可以使用这个:

    db.collection.aggregate([
       { $set: { data: [{ k: "$status", v: "$count" }] } },
       {
          $replaceRoot: {
             newRoot: {
                $mergeObjects: [
                   { $arrayToObject: "$data" }, { article_id: "$article_id" }
                ]
             }
          }
       },
       {
          $group: {
             _id: "$article_id",
             status: { $push: "$$ROOT" }
          }
       },
       { $set: { status: { $mergeObjects: ["$status"] } } },
       { $replaceRoot: { newRoot: "$status" } },
    ])
    

    Mongo playground

    【讨论】:

      【解决方案2】:

      试试这个代码

       db.getCollection('artwork').aggregate([
        {
          $group: {
            _id: '$article_id',
            FAILED: {
              '$sum': {
                "$cond": [{ "$eq": ["$status", "FAILED"] }, 1, 0]
              }
            },
            DELIVERED: {
              '$sum': {
                "$cond": [{ "$eq": ["$status", "DELIVERED"] }, 1, 0]
              }
            }
          }
        }
      ])
      

      mongoplayground

      【讨论】:

      • 我认为你必须使用{$sum: {... "$count",0}} 而不是{$sum: {... 1,0}}
      【解决方案3】:
       {
         $group:{
           _id:"$_id",
           articleId:{$addToset:"$article_id"},
           failed:{$addToset:"$failed"},
           delivered:{$addToset:"$delivered"}
      
         }
       },
       { $addFields:{ 
          article_id:{$size:articleId},
          fail:{$size:"$faild"},
          deliver:{$size:"$faild"},
         }
      

      在 $addToSet 组中将返回数组,在 addField 中将返回数组的总长度。你可以在 mongo 中搜索 $size }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-30
        • 1970-01-01
        • 2019-03-09
        • 2021-11-08
        • 2016-11-24
        • 2017-09-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多