【发布时间】:2017-09-13 00:56:42
【问题描述】:
我无法理解 $aggregation 方法在 Mongoose 中的工作原理。老实说,我在 mongoose 文档中找不到任何代码示例(我什至在他们的网站上都没有找到 [search] 选项 [google site:mongoosejs.com 帮助我])
所以,我希望有人能帮我解释一下并回答我的问题。
例如,我的收藏中有各种文档,带有字段:
{ "_id": 1, "item":47139, "total_price": 560000, "quantity": 56, "lastModified" : 1491748073000 }
{ "_id": 3, "item":47140, "total_price": 1750000, "quantity": 150, "lastModified" : 1491748073000 }
我想$sumid: 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
});
但是可以通过猫鼬来执行此操作吗?根据 mongo docs,我应该使用此代码来匹配必要的文档数组,如下所示:
server.aggregate().match({
lastModified : 1491748073000,
item : 47139
}).exec(function (err, result){
console.log(result);
console.log(err);
});
然后使用$group 对必要的数据和{ $sum: "quantity" } 进行分组,但接下来我应该做什么?如果我只想接收所有数量的总和,为什么要使用 $group?
谁能告诉我我错过了什么?
【问题讨论】:
标签: javascript json node.js mongodb mongoose