如何在MongoDB中获取百分比

问题描述 投票:0回答:1

分组后的文档样本。

[
  {
    "_id": {
      workhour: 1
    },
    totalChats: 156
  },
  {
    "_id": {
      workhour: 0
    },
    totalChats: 36
  }
]

组装后的文档样本图片

你好!我怎么才能找到这2个对象的百分比呢,最后的结果应该是。

[
  {
    "totalChats": 192,
    "workhour0": 19,
    "workhour1": 81
  }
]

谢谢您!

mongodb aggregate percentage
1个回答
1
投票

你需要至少有MongoDB的版本。4.0 做到这一点,因为使 {workhour : 1} 形成 workhour1 你需要连接 workhour 连串 1因此,要转换 1 到字符串,你需要使用 $toString 只有在>=中才有。4.0. 你需要在你的 $group 阶段 :

db.collection.aggregate([
    {
      $group: {
        _id: "", // Group without any condition will group all docs
        docs: { $push: { workhour: "$_id.workhour", totalChats: "$totalChats" } // push {workhour :...,totalChats:...} objects to data array
        },
        totalChats: { $sum: "$totalChats" } // Sum-up `totalChats` across all docs
      }
    },
    {
      $project: {
        _id: 0,
        totalChats: 1,
        data: {
          $arrayToObject: { // Converts [{k :..., v:...}, {k :..., v:...}] into {k : v, k:v }
            $map: { // Pushing objects {k:...,v:...} to an array
              input: "$docs",
              in: { k: { $concat: [ "workhour", { $toString: "$$this.workhour" } ] }, v: { $multiply: [ { $divide: [ "$$this.totalChats", "$totalChats" ] }, 100 ] } }
            }
          }
        }
      }
    },
    /** Replace root of doc with newly created object */
    {
      $replaceRoot: { newRoot: { $mergeObjects: [ "$data", { totalChats: "$totalChats" } ] } }
    }
  ])

阶段:测试: mongoplayground

参考文献 : 聚合运营商

注意: 你应该保持 18.75 原样,而不是将其转换为 19 &amp。81.2581 以免造成任何不确定性。

© www.soinside.com 2019 - 2024. All rights reserved.