我正在try 在聚合管道内的一个对象中将两个金额相加.

这是我的Sandbox :https://mongoplayground.net/p/LIvksL-UGur

文档:

[
  {
    "result": {
      "invoices": [
        {
          "product": "baseball",
          "amount": 4,
          "tax": 1
        },
        {
          "product": "basketball",
          "amount": 10,
          "tax": 2
        }
      ]
    }
  }
]

我希望结果是:

[
  {
    "result": {
      "invoices": [
        {
          "product": "baseball",
          "amount": 4,
          "tax": 1,
          "total": 5
        },
        {
          "product": "basketball",
          "amount": 10,
          "tax": 2,
          "total": 12
        }
      ]
    }
  }
]

我觉得应该这样:

db.collection.aggregate([
  {
    $set: {
      "result.invoices": {
        "total": "$result.invoices.amount + $result.invoices.tax"
      }
    }
  }
])

总数为空,因为它试图添加两个数组,我通过try 以下命令来理解这一点:

db.collection.aggregate([
  {
    $set: {
      "result.invoices": {
        "total": "$result.invoices.amount"
      }
    }
  }
])

...这给了我们这个机会:

[
  {
    "result": {
      "invoices": [
        {
          "product": "baseball",
          "amount": 4,
          "tax": 1,
          "total": [
             4,
             10
           ]
        },
        {
          "product": "basketball",
          "amount": 10,
          "tax": 2,
          "total": [
             4,
             10
           ]
        }
      ]
    }
  }
]

我怎样才能以正确的方式go 做呢?

注:我意识到这是一个非常简单的例子,我可以在得到结果后添加计算.这只是说明了我正在努力解决的一个更复杂的问题.

推荐答案

因为result.invoices是一个数组字段,所以您需要使用$map来迭代元素,并使用$mergeObjects来将total字段追加到那里.

db.collection.aggregate([
  {
    $set: {
      "result.invoices": {
        "$map": {
          "input": "$result.invoices",
          "as": "i",
          "in": {
            "$mergeObjects": [
              "$$i",
              {
                "total": {
                  $sum: [
                    "$$i.amount",
                    "$$i.tax"
                  ]
                }
              }
            ]
          }
        }
      }
    }
  }
])

Mongo Playground

Mongodb相关问答推荐

用其他集合中的文档替换嵌套文档数组中的值

我可以在BSON中使用代理字段吗?

在MongoDB中是否可以按递增顺序更新多个文档?

MongoDB:就地分组嵌套数组的元素

在mongdob中按子文档筛选不起作用

MongoDB $lookup 查找字段值数组

Golang中的Mongo中值运算

Mongo查找条件:不存在

Mongo,通过 Lookup 计算多个文档中数组中的项目

为什么使用 Golang Mongo 驱动程序进行简单查询需要超过 2 秒?

如何在mongoDB中按嵌套文档分组( group by )

如何在 Mongo 聚合管道中获取限制之前的计数

Mongoose $push 不断添加两个条目

pymongo 排序和 find_one 问题

Node.js 和 MongoDB,重用 DB 对象

mongodb:upserting:仅在插入文档时设置值

mongodb: UnknownError assertion src/mongo/db/server_options_helpers.cpp:355

使用 Node.js 将许多记录插入 Mongodb 的正确方法

MongoDB聚合框架的索引优化

即使重新安装后,Mongo 仍在等待 27017