【问题标题】:How to aggregate MongoDB the final total sum? From the sum calculated earlier如何聚合 MongoDB 的最终总和?从之前计算的总和
【发布时间】:2021-04-20 03:35:13
【问题描述】:

如何汇总最终的总和?从前面计算的总和

这是原始结果。

[
  {
    "name": "a",
    "prices": 10,
  },
  {
    "name": "a",
    "prices": 20,
  }
]

但我需要这样做。

[
  {
    "name": "a",
    "prices": 10,
  },
  {
    "name": "a",
    "prices": 20,
  },
//i need to do more//
  {
    "name": "total",
    "total":30
  }

]

这是示例图片。

enter image description here

【问题讨论】:

  • 请添加示例文档和用于第一个结果集的查询。
  • @TusharGupta-curioustushar 我添加了一个示例图像以使其更易于理解。谢谢你看我的问题。 i.stack.imgur.com/gJ3pu.png
  • 原始结果是否意味着这些是数据库中的文档?还是聚合管道的结果?
  • 我查询数据库中的文档。到 jsonString 并把它放在 csv 中。

标签: java mongodb mongoose mongodb-query aggregation-framework


【解决方案1】:
  • $group 通过 null 并在 docs 中构造根文档数组,在 totalPrices 中获取总价格
  • concat 当前docs 和使用$concatArrays 的总价格文档
  • $unwind解构docs数组
  • $project 显示来自 docs 对象的两个字段
db.collection.aggregate([
  {
    $group: {
      _id: null,
      docs: { $push: "$$ROOT" },
      totalPrices: { $sum: "$prices" }
    }
  },
  {
    $project: {
      docs: {
        $concatArrays: [
          "$docs",
          [
            {
              name: "total",
              prices: "$totalPrices"
            }
          ]
        ]
      }
    }
  },
  { $unwind: "$docs" },
  {
    $project: {
      _id: 0,
      name: "$docs.name",
      prices: "$docs.prices"
    }
  }
])

Playground

【讨论】:

  • 非常感谢您的回答和解释。
  • 太棒了,不错的一个++
猜你喜欢
  • 2013-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-27
  • 1970-01-01
  • 2019-02-22
  • 1970-01-01
相关资源
最近更新 更多