ID大于10的文档的值域的平均值

我使用express,nodejs和尚。

集合由对象组成: {_id, valueField}

假设_id在插入时被覆盖,并且收集范围从1到5的5个文档的id都是整数。

这就是我现在正在尝试 – 但我相信语法是不正确的。 该函数返回错误500,甚至不会到达console.log(e)。

我想查找_id大于10的集合中的所有对象。

 collection.aggregate([ { $match: { "_id":{$gt: 3} }}, { $group: { _id: null, flow: { $avg: "$value" } }} ], function (e, docs) { if (e) { console.log(e); return; } console.log(docs); res.json(docs); }); 

我之前写的一个函数来获取id高于10的所有元素都可以正常工作:

 collection.find({"_id":{$gt: 3}}, {}, function(e,docs){ res.json(docs); }); 

collections内容:

 { "_id": 1, "value": 10 } { "_id": 2, "value": 5 } { "_id": 3, "value": 4 } { "_id": 4, "value": 12 } { "_id": 5, "value": 10 } 

预期结果:

 { "_id": null, "value": 11 } 

Arrgh! 应该早点看到这个。 抱歉。

您需要.aggregate().col访问器:

 var db = require('monk')('localhost/test'); var junk = db.get('junk'); junk.col.aggregate( [ { "$match": { "_id": { "$gt": 3 } } }, { "$group": { "_id": null, "flow": { "$avg": "$value" } }} ], function(err,docs) { if (err) throw err; console.log( JSON.stringify( docs, undefined, 2 ) ); } ); 

由于.aggregate()在原生“Monk”API下不是本地支持的function,因此需要深入到底层的“Node Native”集合中。

十分抱歉。