Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What aggregation cursor methods are supported by Nodejs drivers?

As you know from 2.6 on Mongodb aggregate() operation returns a cursor, however the behavior is a bit different than the normal cursor which returns from a find(). I am using native mongodb nodejs driver, and could not find a proper documentation on available aggregate cursor methods.

For example, one cannot run a count() on an aggregation cursor however there are two methods such cursor.objsLeftInBatch() and cursor.itcount() n mongo shell. I could not find any of them in the source code of nodejs native driver. What aggregation cursor methods are supported by Nodejs native driver or Mongoose?

like image 605
anvarik Avatar asked Mar 19 '23 11:03

anvarik


1 Answers

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.

like image 104
Neil Lunn Avatar answered Mar 22 '23 18:03

Neil Lunn