我有两种猫鼬模型:用户和一种与之相关的活动
用户架构
let userSchema = new mongoose.Schema({
name: { type: String, required: true },
clan: { type: String },
activities: [{
type: mongoose.Schema.ObjectId,
ref: 'Activity',
}],
});
活动架构
let activitySchema = new mongoose.Schema({
name: { type: String },
point: { type: Number },
});
所以数据是这样的
[{
name: "Player A",
clan: "Some Clan",
activities: [{
name: "Wake up",
point: 5
},{
name: "Eat,
point: 3
}]
},{
name: "Player B",
clan: "Some Clan",
activities: [{
name: "Wake up",
point: 5
},{
name: "Sleep",
point: 5
}]
}]
现在,我如何总结所有玩家在“ Some Clan”氏族中的分数?
我期望这样的结果
{
sumOfPoints: 18 // because sum of player activities in "Some Clan" is 5 + 3 + 5 + 5
}
像这样的表单查询:
db.user.aggregate({$match:{clan:"Clan A"}},
{$unwind: {path:"$activity"}},
{$lookup:{from: "activityCollection", localField: "activity._id", foreignField:"_id", as:"activityData"}},
{$unwind: {path: "$activityData" }},
{$group:{
_id:"$_id",
name: {$first: "$name"},
clan: {$first: "$clan"},
totalPoints:{$sum:"$activityData.points"}
}}).pretty()
说明:
首先,我在$unwind
集合的activity
字段上使用users
,因为它是一个数组,我们要对活动数组中的_id字段执行$lookup
。
[执行$lookup
之后,我在查询结果上使用了$unwind
,
和$group stage
$sum accumulator
来添加点。希望这可以帮助您找到答案。