mongodb 总平均

fruv7luv  于 2023-11-17  发布在  Go
关注(0)|答案(1)|浏览(220)

我想合计一笔收款的平均值乘以金额。以下是示例文档:

[
  {
    _id: new ObjectId("653c4c017800342a3bedb82e"),
    item: 555,
    amount: 1,
    priceEach: 100000
  },
  {
    _id: new ObjectId("653c4c017800342a3bedb830"),
    item: 384,
    amount: 2,
    priceEach: 70000
  },
  {
    _id: new ObjectId("653c4c017800342a3bedb830"),
    item: 384,
    amount: 3,
    priceEach: 50000
  }
]

字符串
这是我到目前为止的结果:

[
  { _id: 366, avg: 3553248.5833333335, amount: 24 },
  { _id: 367, avg: 13565500, amount: 2 },
  { _id: 533, avg: 4286751.2, amount: 11 },
  { _id: 555, avg: 4718763.357142857, amount: 22 },
  { _id: 273, avg: 11000, amount: 57 },
  { _id: 283, avg: 23882000, amount: 8 },
  { _id: 370, avg: 4000000, amount: 2 }
]


问题是,我没有考虑到该价格的商品可用频率。在这个具体的例子中,我想计算19 * 70000和10 * 50000的平均值。我以前的聚合看起来像这样,但这里没有考虑金额:

const res = await Log.aggregate([
      {
        $match: { user: new ObjectId('653c3906012fec5ace3e54e2'), type: 'buy' }
      },
      {
        $group: {
          _id: '$item',
          avg: { $avg: '$priceEach' },
          amount: { $sum: '$amount' }
        }
      }
    ])


如果我在70000和50000处分别有384项2x和3x,我想计算[70000,70000,50000,50000,50000]的平均值。

sczxawaw

sczxawaw1#

感谢cmgchess,最终的聚合看起来像这样:

Log.aggregate([
      {
        $match: { user: new ObjectId('653c3906012fec5ace3e54e2'), type: 'buy' }
      },
      {
        $group: {
          _id: '$item',
          totalPrice: {
            $sum: {
              $multiply: [
                '$priceEach',
                '$amount'
              ]
            }
          },
          totalAmount: {
            $sum: '$amount'
          }
        }
      },
      {
        $project: {
          _id: 1,
          avg: {
            $divide: [
              '$totalPrice',
              '$totalAmount'
            ]
          },
          amount: '$totalAmount'
        }
      }
    ])

字符串

相关问题