Node.js - 如何计算mongodb中子文档的聚合(总和)?

时间:2014-08-20 11:34:27

标签: node.js mongodb mongoose aggregation-framework

我的收藏结构是,

[{
    "_id": "....",
    "name": "aaaa",
    "level_max_leaves": [{
        level: "ObjectIdString 1",
        max_leaves: 4,
    }]
}, {
    "_id": "....",
    "name": "bbbb",
    "level_max_leaves": [{
        level: "ObjectIdString 1",
        max_leaves: 4,
    }]
}, {
    "_id": "....",
    "name": "cccc",
    "level_max_leaves": [{
        level: "ObjectIdString 1",
        max_leaves: 7,
    }]
}, {
    "_id": "....",
    "name": "dddd",
    "level_max_leaves": [{
        level: "ObjectIdString 2",
        max_leaves: 3,
    }]
}]

现在我需要将具有max_leaves的{​​{1}}字段相加?

ObjectIdString 1的结果。

到目前为止我试过

(4+4+7=15)

如何实现这一目标?

1 个答案:

答案 0 :(得分:2)

通常,在聚合框架中处理数组时,首先需要$unwind数组内容。这"去标准化"作为单独文件的内容。从这里开始,正常的分组操作按预期工作:

MyModel.aggregate([

    // Unwind to "de-normalize"
    { "$unwind": "$level_max_leaves" },

    // Group as expected
    { "$group": {
        "_id": "$level_max_leaves.level",
        "total": { "$sum": "$level_max_leaves.max_leaves" }
    }}

],function(err,result) {

    // process results here

});

另请注意"绝对"寻址元素时需要路径。