【问题标题】:How to sum field when use group mongoose?使用组猫鼬时如何对字段求和?
【发布时间】:2018-04-02 13:30:26
【问题描述】:

我在后面有文档 mongoDB。

{ "_id" : ObjectId("5ac06b6fb49124f4e5602817"), "status" : -1, "createdAt" : ISODate("2018-03-31T05:17:35.557Z") }

{ "_id" : ObjectId("5ac0b51cb08b6c0014d1d0c1"), "status" : 0, "createdAt" : ISODate("2018-04-01T10:31:56.199Z") }

{ "_id" : ObjectId("5ac0b538b08b6c0014d1d0c2"), "status" : 2, "createdAt" : ISODate("2018-04-01T10:32:24.542Z") }

我使用了 $group、$match、$sum 并且我只能返回: { _id: { month: 4, day: 1, year: 2018 }, count: 2 }

我想退货: { _id: { month: 4, day: 1, year: 2018 }, count : 2, countStatus0 : 1, countStatus2 : 1 }

希望你能帮助我... 太感谢了。 对不起,我的英语不好。

【问题讨论】:

    标签: mongodb mongoose mongodb-query


    【解决方案1】:

    您可以尝试以下聚合:

    db.col.aggregate([
      {
        $group: {
          _id: {
            year: { $year: "$createdAt" },
            month: { $month: "$createdAt" },
            day: { $dayOfMonth: "$createdAt" },
            status: "$status"
          },
          count: { $sum: 1 }
        }
      },
      {
        $group: {
          _id: {
            year: "$_id.year",
            month: "$_id.month",
            day: "$_id.day"
          },
          count: { $sum: "$count" },
          statuses: { $push: { k: { $concat: ["status", {$substr:["$_id.status", 0, -1 ]}] }, v: "$count" } }  
        }
      },
      {
        $project: {
          _id: 1,
          count: 1,
          statuses: { $arrayToObject: "$statuses" }
        }
      },
      {
        $replaceRoot: {
          newRoot: {
            $mergeObjects: [ "$$ROOT", "$statuses" ]
          }
        }
      },
      {
        $project: {
          statuses: 0
        }
      }
    ])
    

    要获得每个状态的总和和总和,您必须使用 $group 两次。每个部分状态都可以转换为一对kv,其中key 是一个动态生成的字符串,它是status 及其值如status0status2 的串联。有了这些对,您可以使用 $arrayToObject 从该数组生成对象字段。然后您可以使用$mergeObjects$replaceRoot 将根与嵌套的statuses 对象合并。

    这里有一个技巧。由于 MongoDB 不允许将字符串与 double 连接,我们必须在 double 上使用 $substr 将其转换为字符串。

    【讨论】:

      猜你喜欢
      • 2019-11-11
      • 2023-03-08
      • 2021-12-21
      • 2014-01-12
      • 1970-01-01
      • 2019-09-14
      • 1970-01-01
      • 2016-05-03
      • 2014-09-10
      相关资源
      最近更新 更多