【问题标题】:How can I get percentage in MongoDB如何在 MongoDB 中获得百分比
【发布时间】:2020-05-16 05:52:54
【问题描述】:

小组赛后的示例文档:

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

Sample docs image after applying group

你好!我怎样才能找到这 2 个对象的百分比? 最终结果应该是:

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

谢谢!

【问题讨论】:

  • 请不要发布代码(或错误)图像。相反,将代码作为代码格式的文本添加到问题本身。示例代码最好是最小的可重现示例。另外,请告诉我们您到目前为止所做的尝试。
  • @Jorge De La Vega Carrasco:你的 MongoDB 版本是多少?
  • 它就像你写的那样工作:) 我的 mongo 高于 4.0

标签: mongodb mongodb-query aggregation-framework


【解决方案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

参考:aggregation-operators

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

【讨论】:

  • 太棒了,你救了我的工作哈哈。谢谢!
猜你喜欢
  • 2021-01-09
  • 1970-01-01
  • 2019-06-08
  • 2012-02-11
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多