mongodb组和总和?

在过去的几个小时里,我一直在为这个问题烦恼,不能把头绕在上面。 也许有人可以帮忙。 我收集了以下内容。

{ "smallparts": [ { "quantity": "10", "part": "test1" }, { "quantity": "10", "part": "test2" } ] }, { "smallparts": [ { "quantity": "10", "part": "test3" } ] }, { "smallparts": [ { "quantity": "10", "part": "test1" }, { "quantity": "10", "part": "test2" } ] } 

当尝试以下添加量我不能正确。

 collection.aggregate( // Unwind the array { "$unwind":"$smallparts" }, // Group the products { "$group": { "_id": { "part": "$smallparts.part", "total": "$smallparts.quantity", } }, }, 

我的输出是这是错误的。 test1和test2应该是20。

 { "data": [ { "_id": { "part": "test3", "total": "10" } }, { "_id": { "part": "test2", "total": "10" } }, { "_id": { "part": "test1", "total": "10" } } ] 

}

我也试过这个,但得到一个空的数组。

collection.aggregate(
//展开数组{“$ unwind”:“$ smallparts”},

 // Group the products { "$group": { "_id": { "part": "$smallparts.part", "total": "$smallparts.quantity", sum: { $sum: "$smallparts.quantity" } } }, 

谢谢你的帮助。

你面临的问题是你不能使用string$sum 。 您需要将您的数量转换为整数才能使此查询生效。

当数量是一个整数时,获得所有总数的总和的方法:

 db.coll.aggregate([ { $unwind : "$smallparts"}, { $group : { _id : "$smallparts.part" , sum : { $sum : "$smallparts.quantity" } } }]); 

如果你有控制数据库模式,这将是build议的方法。

第二种方法是使用map-reduce重写您的查询,您可以使用JavaScript函数(如parseInt来转换值:

 var mapFunction = function() { for (var idx = 0; idx < this.smallparts.length; idx++) { emit(this.smallparts[idx].part, this.smallparts[idx].quantity); } }; var reduceFunction = function(key, vals) { var sum = 0; for (var idx = 0; idx < vals.length; idx++) { sum += parseInt(vals[idx]); } return sum; }; db.coll.mapReduce(mapFunction, reduceFunction, { out : "my_mapreduce_res"}); 

您的map-reduce结果将存储在my_mapreduce_res集合中。