条件中的表达式

Expression within condition

提问人:OliverKhl 提问时间:10/28/2023 更新时间:10/28/2023 访问量:19

问:

这是一个后续问题:

我只想聚合类型为“buy”的文档的集合平均值。 所以问题是如何获得 sum 表达式周围的 if 条件,并且 totalBuyAmount 也是如此。检查代码:)中的注释

以下是示例文档:

[
  {
    _id: ObjectId("653c4c017800342a3bedb82e"),
    type: 'buy',
    item: 555,
    amount: 1,
    priceEach: 100000
  },
  {
    _id: ObjectId("653c4c017800342a3bedb830"),
    type: 'buy',
    item: 384,
    amount: 2,
    priceEach: 70000
  },
  {
    _id: ObjectId("653c4c017800342a3bedb831"),
    type: 'buy',
    item: 384,
    amount: 1,
    priceEach: 50000
  },
  {
    _id: ObjectId("653c4c017800342a3bedb831"),
    type: 'sell',
    item: 384,
    amount: -1,
    priceEach: 50000
  }
]

只有当键入==='buy'时,我才需要totalBuyPrice

db.collection.aggregate([
  {
    $group: {
      _id: "$item",
      totalBuyPrice: {
        $sum: { // Only if type === 'buy'
          $multiply: [
            "$priceEach",
            "$amount"
          ]
        }
      },
      totalBuyAmount: // $sum $amount if type === 'buy'
      totalAmount: {
        $sum: "$amount"
      }
    }
  },
  {
    $project: {
      _id: 1,
      avg: {
        $divide: [
          "totalBuyPrice",
          "totalBuyAmount"
        ]
      },
      amount: "$totalAmount"
    }
  }
])
node.js mongodb mongoose 聚合

评论


答:

1赞 Yong Shun 10/28/2023 #1

您可以添加运算符以根据条件执行计算。$cond

db.collection.aggregate([
  {
    $group: {
      _id: "$item",
      totalBuyPrice: {
        $sum: {
          $cond: [
            {
              $eq: [
                "$type",
                "buy"
              ]
            },
            {
              $multiply: [
                "$priceEach",
                "$amount"
              ]
            },
            0
          ]
        }
      },
      totalBuyAmount: {
        $sum: {
          $cond: [
            {
              $eq: [
                "$type",
                "buy"
              ]
            },
            "$amount",
            0
          ]
        }
      },
      totalAmount: {
        $sum: "$amount"
      }
    }
  },
  {
    $project: {
      _id: 1,
      avg: {
        $divide: [
          "$totalBuyPrice",
          "$totalBuyAmount"
        ]
      },
      amount: "$totalAmount"
    }
  }
])

演示 @ Mongo Playground

评论

0赞 OliverKhl 10/28/2023
效果很好,我非常接近解决方案:)