这是一个后续问题:
我只想聚合类型为“购买”的文档的集合平均值。 所以问题是如何获得总和表达式周围的 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"
}
}
])