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

问题描述 投票:0回答:1

我有两种猫鼬模型:用户和一种与之相关的活动

用户架构

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
}
node.js mongodb mongoose aggregation-framework
1个回答
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,因为它是一个数组,我们要对活动数组中的_id字段执行$lookup

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

$group stage

中,使用$sum accumulator来添加点。

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

© www.soinside.com 2019 - 2024. All rights reserved.