如何对子文档中的字段求和+;MongoDB+;Javascript?

如何对子文档中的字段求和+;MongoDB+;Javascript?,javascript,node.js,mongodb,mapreduce,Javascript,Node.js,Mongodb,Mapreduce,你能帮我解答这个问题吗?如何对以下文档中的数量字段求和?我已经写了一段代码,当您访问价格、年龄等时,它似乎工作正常,但当您访问子文档时,它似乎工作不正常。在这种情况下,total=0` 文件: { "_id" : ObjectId("50a8240b927d5d8b5891743c"), "cust_id" : "abc123", "status" : "A", "price" : 75, "age" : 24, "ord_date" : "02/02/2012", "items" : [

你能帮我解答这个问题吗?如何对以下文档中的
数量
字段求和?我已经写了一段代码,当您访问
价格
年龄
等时,它似乎工作正常,但当您访问子文档时,它似乎工作不正常。在这种情况下,
total
=0`

文件:

{
"_id" : ObjectId("50a8240b927d5d8b5891743c"),
"cust_id" : "abc123",
"status" : "A",
"price" : 75,
"age" : 24,
"ord_date" : "02/02/2012",
"items" : [ 
    {
        "sku" : "mmm",
        "qty" : 5,
        "price" : 2.5
    }, 
    {
        "sku" : "nnn",
        "qty" : 500,
        "price" : 50
    }
]
}

代码:

 exports.test = function(collection, callback) {

 MongoClient.connect(url, function(err, db) {
    assert.equal(null, err);
    db.collection(collection).aggregate(

        {
            $match : { "price" : { $gt: 70, $lt: 90 }}
        },
        { 
            $group : { total: { $sum: "$items.qty" }}
        },
    function(err, result) {
        console.log("result",result);
        if (result) {
            callback(result);
        } else {
            callback(false);
        }  
    });
});
}
谢谢你的帮助


谢谢,

您需要在分组之前添加
{$unwind items}
。这应该可以解决问题。

如果在命令提示符下使用,应该可以:-

db.inventory.aggregate([
{$unwind: "$items"},
{$match: {"items.price" : { $gt: 70, $lt: 90 }}},
{$group:{_id:"$_id","total": {$sum:"$items.price"}}}
])
尝试使用“展开”功能。
我已经按照您的建议插入了这段代码,但不幸的是,这不起作用。db.collection(collection).aggregate({$unwind:$items},{$match:{“price”:{$gt:70,$lt:90}}}),匹配结果后的展开仍然未定义。{$match:{“price”:{$gt:70,$lt:90},{$unwind:$items},{$group:{total:{$sum:“$items.qty”}},您是否在分组阶段指定了一个id。比如{{u id:cust.id,total:…}?这是我在我的代码.db.collection(collection).aggregate({$match:{“price”:{$gt:70,$lt:90}},{$unwind:$items},{$group:{total:{$sum:$items.qty}}}},函数(err,result){
exports.test = function(collection, callback) {

 MongoClient.connect(url, function(err, db) {
    assert.equal(null, err);
    db.collection(collection).aggregate(
        {$unwind: "$items"} ,
        {
            $match : { "items.price" : { $gt: 70, $lt: 90 }}
        },
        { 
            $group : { _id:null,total: { $sum: "$items.qty" }}
        },
    function(err, result) {
        console.log("result",result);
        if (result) {
            callback(result);
        } else {
            callback(false);
        }  
    });
});
}