【问题标题】:How To Get Sum Of Value Field in Associated Document如何获取关联文档中的值字段总和
【发布时间】:2019-10-27 14:15:03
【问题描述】:

我有两个 Mongoose 模型:用户模型和与之关联的活动模型

用户架构

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
    }]
}]

现在,我如何将玩家在氏族“某些氏族”中的所有玩家积分相加?

我期待这样的结果

{
     sumOfPoints: 18 // because sum of player activities in "Some Clan" is 5 + 3 + 5 + 5
}

【问题讨论】:

    标签: node.js mongodb mongoose aggregation-framework


    【解决方案1】:

    这样的表单查询:

    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()
    

    说明:

    首先,我在users 集合中的activity 字段上使用了$unwind,因为它是一个数组,我们希望使用_id 字段执行$lookup来自活动数组。

    在执行$lookup 之后,我在查找结果中使用了$unwind,

    在$group stage中,使用$sum accumulator来加分。

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

    【讨论】:

      猜你喜欢
      • 2022-11-24
      • 1970-01-01
      • 2020-09-06
      • 2012-01-04
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多