我在理解 $aggregation
方法在 Mongoose 中的工作方式时遇到问题。老实说,我在 mongoose 文档中找不到任何代码示例(我在他们的网站上什至没有找到 [search] 选项 [google site:mongoosejs.com helps me])
所以,我希望有人能帮我解释一下并回答我的问题。
例如,我的集合中有各种文档,字段为:
{ "_id": 1, "item":47139, "total_price": 560000, "quantity": 56, "lastModified" : 1491748073000 }
{ "_id": 3, "item":47140, "total_price": 1750000, "quantity": 150, "lastModified" : 1491748073000 }
并且我想$sum
具有id: 47139
和timestamp: 1491748073000
的文档的所有“数量”。至于现在这段代码工作正常并为我提供了必要的数据:
var server = mongoose.model('Name_of_my_Schema', Schema);
server.find({ lastModified : 1491748073000, item : 47139 }, null, {sort: 'buyout'},function (err, res) {
total = 0;
for (i = 0; i < res.length; i++) { //sorry, map.reduce, but not this time
total += res[i].quantity;
}
console.log(total); //in this case total = 256
});
但是否可以通过 mongoose 执行此操作?根据 mongo 文档,我应该使用此代码来匹配必要的文档数组,如下所示:
server.aggregate().match({
lastModified : 1491748073000,
item : 47139
}).exec(function (err, result){
console.log(result);
console.log(err);
});
然后使用$group
将必要的数据和{ $sum: "quantity"}
分组,但是接下来我应该做什么?如果我只想收到所有数量的总和,为什么要使用 $group?
有人可以告诉我我错过了什么吗?
最佳答案
正如您所说的那样,您错过了 $group
管道步骤进行总和聚合。按照以下方式完成管道:
server.aggregate()
.match({
"lastModified": 1491748073000,
"item": 47139
})
.group({
"_id": null,
"total": { "$sum": "$quantity" }
})
.exec(function (err, result){
console.log(result);
console.log(err);
});
或作为运算符数组:
server.aggregate([
{ "$match": { "lastModified": 1491748073000, "item": 47139 } },
{ "$group": { "_id": null, "total": { "$sum": "$quantity" } } }
]).exec(function (err, result){
console.log(result);
console.log(err);
});
关于javascript - MongoDB Mongoose 聚合/数学运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43450940/