[英]How to sum the fields in a sub document + MongoDB + Javascript?
Could you kindly help me with this query? 您能帮我这个疑问吗? How do I sum the
qty
field in the below document? 如何
qty
以下文档中的qty
字段? I have written a piece of code which seems to work when you're accessing price
, age
etc but it seems to not work well when you are accessing sub documents. 我编写了一段代码,当您访问
price
, age
等时,该代码似乎起作用,但在访问子文档时,它似乎无法正常工作。 Here in this case total
= 0`. 在这种情况下,
total
= 0`。
Document: 文献:
{
"_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);
}
});
});
}
Appreciate your help! 感谢您的帮助!
Thank you, 谢谢,
You need to add {$unwind items}
before grouping. 分组之前,您需要添加
{$unwind items}
。 That should do the trick. 这应该够了吧。
This should work if used from the command prompt: - 如果在命令提示符下使用它,则该方法应该起作用:-
db.inventory.aggregate([
{$unwind: "$items"},
{$match: {"items.price" : { $gt: 70, $lt: 90 }}},
{$group:{_id:"$_id","total": {$sum:"$items.price"}}}
])
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);
}
});
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.