在node.js-mongodb中分组

use*_*943 1 mongodb node.js mongodb-query aggregation-framework monk

我想在我的server.js中使用group by,但是我收到此错误:

TypeError:Object #(Collection) has no method 'group'
Run Code Online (Sandbox Code Playgroud)

我在网上看了看这个功能的名字.

这是我写的:

var monk = require('monk');
var db = monk('localhost:27017/Messages');
var collection = db.get('col');
collection.group(['a'], {}, {}, {}, function (e, docs) {
  res.json(docs);
});
Run Code Online (Sandbox Code Playgroud)

谁能告诉我什么是错的?谢谢!

Nei*_*unn 5

Monk没有自己实现一个.group()方法,但是有一个.col访问器可用,你可以从底层驱动程序中获取本机Collection对象并使用它的方法.

您的用法.group()有点偏,所以我将使用我的数据示例:

{
    "_id" : ObjectId("5479c4793815a1f417f537a0"),
    "status" : "canceled",
    "date" : ISODate("2014-11-29T00:00:00.000Z"),
    "offset" : 30,
},
{
    "_id" : ObjectId("5479c4793815a1f417d557a0"),
    "status" : "done",
    "date" : ISODate("2014-10-20T00:00:00.000Z"),
    "offset" : 30,
},
{
    "_id" : ObjectId("5479c4793815a1f417f117a0"),
    "status" : "done",
    "date" : ISODate("2014-12-29T00:00:00.000Z"),
    "offset" : 30,
}
Run Code Online (Sandbox Code Playgroud)

然后你可以编写这样的.group()语句:

  var db = require('monk')('localhost/test'),
      sample = db.get('sample');

  sample.col.group(
    ["status"],
    {},
    { "count": 0 },
    "function (obj,prev) { prev.count++; }",
    function(err,docs) {
      if (err) console.log(err);
      console.log( docs );
    }
  );
Run Code Online (Sandbox Code Playgroud)

但这也表明99%的时间你可能真的想要这个.aggregate()方法:

  var db = require('monk')('localhost/test'),
      sample = db.get('sample');

  sample.col.aggregate(
      [
          { "$group": {
              "_id": "$sample",
              "count": { "$sum": 1 }
          }}
      ],
      function(err,docs) {
         if (err) console.log(err);
         console.log( docs );
      }
  );
Run Code Online (Sandbox Code Playgroud)

.group()与解释JavaScript 相比,聚合框架通常比运行本机代码运算符更灵活,因此它非常值得学习.