如何根据特定条件在mongodb聚合中进行$sum或$subtract
假设我有一个这样的模型如何根据特定条件在mongodb聚合中进行$sum或$subtract,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,假设我有一个这样的模型 userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true, }, points: { type:Number, required: true, }, wonOrLost:{ type: String, required: true, enum: ['won', 'lost', 'noResults'], de
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true,
},
points: {
type:Number,
required: true,
},
wonOrLost:{
type: String,
required: true,
enum: ['won', 'lost', 'noResults'],
default: 'noResults',
},
然后我得到了如下的聚合代码:
let _points = await Points.aggregate([
{ $match: {
userId: user._id ,
wonOrLost: { $ne: "noResults" }
}},
{ $group: {
_id: "$userId",
// here(totalPoints) I want to add points if wonOrLost == 'won' and subtract if wonOrLost == 'lost'
totalPoints: { $sum: "$points" },
}}
])
下面是我使用的方法,如果在求和之前匹配失败,策略是将
点
乘以-1
let _points = await Points.aggregate([
{
$match: {
userId: user._id,
wonOrLost: {$ne: 'noResults'}
}
},
{
$group: {
_id: '$userId',
totalPoints: {$sum: {$cond: [{$eq: ["$wonOrLost", "won"]}, '$points', {$multiply: ['$points', -1]}]}},
}
}
]);