首页 > 解决方案 > mongodb加减一查询(减去两个查询结果)

问题描述

我有以下收藏:

[

{
    "type": "debit",
    "amount": 10
},
{
    "type": "debit",
    "amount": 20
},
{
    "type": "credit",
    "amount": 5
},
]

我需要将所有具有借方类型和减去贷方总和的文件相加。

我如何用 mongodb 处理这个问题?

所以我的预期结果是 25

标签: mongodb

解决方案


db.collection.aggregate([
  {
    "$group": {
      "_id": "$type",
      "field": {
        $sum: {
          "$cond": {
            "if": {
              "$eq": [
                "$type",
                "debit"
              ]
            },
            "then": "$amount",
            "else": {
              "$multiply": [
                "$amount",
                -1
              ]
            }
         }
        }
      }
    }
  },
  {
    "$group": {
      "_id": null,
      "result": {
        "$sum": "$field"
      }
    }
  }
])

https://mongoplayground.net/p/cfTixd1Oo_z


推荐阅读