Nodejs驱动程序支持哪些聚合游标方法?

anv*_*rik 4 mongoose mongodb node.js node-mongodb-native

正如您在2.6上看到的Mongodb aggregate()操作返回一个游标,但是行为与从a返回的普通游标有点不同find().我使用本机mongodb nodejs驱动程序,并找不到有关可用聚合游标方法的正确文档.

例如,一个不能运行count()在汇聚光标然而,有两种方法,例如cursor.objsLeftInBatch()cursor.itcount()Ñ蒙戈壳.我在nodejs本机驱动程序的源代码中找不到它们中的任何一个.Nodejs本机驱动程序或Mongoose支持哪些聚合游标方法?

Nei*_*unn 6

使用游标从聚合返回的实际内容是节点转换流接口以及一些其他便捷方法,特别是:

explain: [Function],
get: [Function],
getOne: [Function],
each: [Function],
next: [Function],
Run Code Online (Sandbox Code Playgroud)

您只需使用转储游标对象即可获得console.log.那些应该是自我解释的get()方法相当于.toArray().

由于这是一个标准的流接口,因此根据此接口可以使用方法和事件处理程序,因此举个例子:

  var MongoClient = require('mongodb').MongoClient;


  MongoClient.connect("mongodb://localhost/test", function(err,db) {

    var items = [];
    var counter = 0;

    var cursor = db.collection('tags').aggregate(
      [
        { "$project": {
          "t1": 1,
          "t2": 1
        }}
      ],
      { "cursor": { "batchSize": 25 } }
    );

    console.log( cursor );

    cursor.on('data', function(data) {
      console.log( this );  // dump the current state info
      items.push( data );
      counter++;
    });

    cursor.on('end', function() {
      console.log( "Iterated " + counter + " times" );
    });

  });
Run Code Online (Sandbox Code Playgroud)

每次游标迭代都会触发"data"事件,对象上的属性将显示流是完整的还是仍在迭代等等.