这是一个跟进问题:

我只想为类型为‘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
  }
]

仅当type=‘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"
    }
  }
])

推荐答案

可以增加$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"
    }
  }
])

Demo @ Mongo Playground

Node.js相关问答推荐

Spotify Auth访问令牌给出错误代码400

GraphQL MongoDB Mongoose填充字段未获取多个类别

编辑Mongoose中的对象嵌套数组

类扩展值[object object]不是构造函数或null

Nestjs swc 错误:找不到模块项目路径/src/app.module

为什么 Cors 在 NodeJS 中不起作用

将图像添加到多个产品的条带 checkout 会话中

Promise 和 Azure 语音转文本

MongoDB:通过匹配输入字符串或输入字符串中的单个单词进行搜索

Gulp 能否向 Docker 发出增量构建的第一次迭代完成的信号?

Typescript 条件语句不过滤值?

在 Atlas 触发器(Node JS)中正确初始化 Firebase 管理 SDK

FirebaseCloudMessaging : PlatformException (PlatformException(null-error, Host platform returned null value for non-null return value., null, null))

如果 express.js (node.js) http 请求在完成之前关闭会发生什么?

如何防止 node.js 中的内存泄漏?

如何正确使用 package.json 中的关键字属性?

如何使用 UglifyJS 缩小文件夹中的多个 Javascript 文件?

运行摩卡+伊斯坦布尔+通天塔

路由后的 Node Express 4 中间件

Google Firebase 错误(函数返回未定义、预期的 Promise 或值)