假设我有一个看起来像的模型
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" },
}}
])
以下是我使用$cond的方法,如果在求和之前匹配失败,策略是将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]}]}},
}
}
]);