id大于10的文档的value字段平均值

Average of value fields of documents with id higher than 10

我正在使用 express、nodejs、monk。

collection 由 objects 组成: {_id, valueField}

假设 _id 在插入时被覆盖,collection 中 5 个文档的 id 范围从 1 到 5。它们都是整数。

这就是我现在正在尝试的 - 但我认为语法不正确。函数 returns 错误 500,甚至从未到达 console.log(e).

我想找到 collection 中 _id 大于 10 的所有 objects。

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);
        });

collection内容:

{
  "_id": 1,
  "value": 10
}

{
  "_id": 2,
  "value": 5
}
{
  "_id": 3,
  "value": 4
}

{
  "_id": 4,
  "value": 12
}
{
  "_id": 5,
  "value": 10
}

预期结果:

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

啊!!应该早点看到这个。对不起。

您需要 .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下不支持作为函数,所以需要"deep dive"到底层"Node Native"集合.

非常抱歉。