What aggregation cursor methods are supported by Nodejs drivers?

杀马特。学长 韩版系。学妹 提交于 2019-12-03 16:31:04

What actually gets returned from aggregate with a cursor is a node transform stream interface with a few other convenience methods, notably:

explain: [Function],
get: [Function],
getOne: [Function],
each: [Function],
next: [Function],

Which you can obtain by simply dumping the cursor object using console.log. Those should be self explanatory with the get() method being equivalent to .toArray().

Since this is a standard streaming interface the methods and event handlers are available as per this interface, so with an example:

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

  });

The "data" event is fired with each cursor iteration and properties on the object will show whether the stream is complete or still iterating and so on.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!