这是一个跟进问题:
我只想为类型为‘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"
}
}
])