从MongoDB中的数组元素中添加值

时间:2018-10-07 10:49:31

标签: mongodb mongodb-query aggregation-framework

我已经进行了一些汇总,以得出给定数据的以下文档结构:

public enum Direction {
    NORTH,
    EAST,
    SOUTH,
    WEST;

    public Direction getOppositeDirection() {
        return Direction.values()[(this.ordinal()+2)%4];
    }

}

但是,我试图将{ "_id" : "test", "NoOfQuestions" : 3.0, "info" : [ { "AnswerrCount" : 3 }, { "AnswerrCount" : 3 }, { "AnswerrCount" : 2 } ] } 列中的所有值加起来。因此,从上面的示例中,我想要另一个列为AnswerrCount的列,然后最终使用TotalAnswers:8, (3+3+2)NoOfQuestions

2 个答案:

答案 0 :(得分:0)

您可以使用$sum聚合来添加数组值

db.collection.aggregate([
  { "$addFields": {
    "TotalAnswers": {
      "$sum": "$info.AnswerrCount"
    },
    "FinalTotal": {
      "$add": [{ "$sum": "$info.AnswerrCount" }, "$NoOfQuestions"]
    }
  }}
])

答案 1 :(得分:0)

db.collection.aggregate([{
    $unwind: "$info"
}, {
    $group: {
        _id: null,
        TotalAnswers: {
            $sum: '$info.AnswerrCount'
        },
        doc: {
            $first: '$$CURRENT'
        }
    }
}, {
    $project: {
        TotalAnswers: 1,
        FinalTotal: {
            '$add': ['$TotalAnswers', '$doc.NoOfQuestions']
        },
        _id: 0
    }
}])