2017-02-26 98 views
0

你能否帮我解决这个问题?我如何总结下面文档中的qty字段?我写了一段代码,当您访问price,age等时似乎工作正常,但在访问子文档时似乎效果不佳。在这种情况下,total = 0`。如何总结子文档+ MongoDB + Javascript中的字段?

文件:

{ 
"_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 
    } 
] 

}

CODE:

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); 
     } 
    }); 
}); 
} 

感谢您的帮助!

谢谢

回答

0

您需要分组之前添加{$unwind items}。这应该够了吧。

+0

我已经按照您的建议插入了一段代码,但不幸的是,这没有奏效。 db.collection(集合).aggregate( { $放松: “$项” },{ $ 匹配:{ “价格”:{$ GT:70,$ LT:90}}} , –

+0

开卷后匹配 –

+0

结果仍然是未定义:( 。{ $匹配:{ “价格”:{$ GT:70,$ LT:90}}} , { $放松: “$项” } , { $ group:{total:{$ sum:“$ items.qty”}} }, –

0

如果从命令提示符下使用这应该工作: -

db.inventory.aggregate([ 
{$unwind: "$items"}, 
{$match: {"items.price" : { $gt: 70, $lt: 90 }}}, 
{$group:{_id:"$_id","total": {$sum:"$items.price"}}} 
]) 
1

尝试这个具有退卷功能。

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); 
     } 
    }); 
}); 
} 
相关问题