使用默认值计算 $sum [英] Calculate $sum with default value
问题描述
我想计算每次特定通话的总支出.
I would like to calculate total spending per specific call.
我正在收集具有特定 callId 的订单,然后从结果中总结 totalPrice 属性.
I am collecting orders with specific callId and then sum totalPrice attributes from the result.
它有效,除非没有订单,否则我会得到一个空数组.我想将 0 作为 totalSpending 的默认值.
It works, except if there is no order, I get an empty array. I would like to get 0 as default value for totalSpending instead.
这是我的查询:
Order.aggregate({
$match: { callId: mongoose.Types.ObjectId(callId) }
}, {
$group: { _id: null, totalSpending: { $sum: '$totalPrice' } }
})
如果没有订单,我会得到一个空数组,如果至少有 1 个订单,我会得到 [ { _id: null, totalSpending: 50 } ]
例如.
If there is no order I get an empty array, if there is at least 1 order I get [ { _id: null, totalSpending: 50 } ]
for example.
推荐答案
你可以试试这样的.
使用 $project
和 $cond
而不是 $match
.这会将不匹配的 callId
文档 totalPrice
覆盖为 0.
Use $project
with $cond
instead of $match
. This overwrites the non-matching callId
document totalPrice
to 0.
Order.aggregate({
$project: {
totalPrice: {
$cond: [{
$eq: ["$callId", mongoose.Types.ObjectId(callId)]
}, "$totalPrice", 0]
}
}
}, {
$group: {
_id: null,
totalSpending: {
$sum: '$totalPrice'
}
}
})
这篇关于使用默认值计算 $sum的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!