如何获取关联文档中的值总和字段

时间:2019-10-27 05:06:14

标签: node.js mongodb mongoose aggregation-framework

我有两种Mongoose模型:一种是用户模型,另一种是与它们相关联的Activity

用户架构

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
}

1 个答案:

答案 0 :(得分:0)

像这样的表单查询:

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 ,因为它是一个数组,我们要执行 {{1} } 和活动数组中的_id字段。

执行$lookup之后,我在查询结果上使用了$lookup

$unwind 中,使用 $group stage 添加点。

希望这可以帮助您找到答案。