Class: AggregationCursor

AggregationCursor

Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly)

Fires:
Returns:
AggregationCursor instance.

Extends

Methods

Set the batch size for the cursor.

Name Type Description
value number

The batchSize for the cursor.

Throws:

Clone the cursor

close(callback){Promise}

Close the cursor, sending a AggregationCursor command and emitting close.

Name Type Description
callback AggregationCursor~resultCallback optional

The result callback.

Returns:
Promise if no callback passed

each(callback){null}

Iterates over all the documents for this cursor. As with {cursor.toArray},
not all of the elements will be iterated if this cursor had been previously accessed.
In that case, {cursor.rewind} can be used to reset the cursor. However, unlike
{cursor.toArray}, the cursor will only hold a maximum of batch size elements
at any given time if batch size is specified. Otherwise, the caller is responsible
for making sure that the entire result can fit the memory.

Name Type Description
callback AggregationCursor~resultCallback

The result callback.

Throws:
Example
// Correctly call the aggregation using a cursor and each

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Some docs for insertion
  var docs = [{
      title : "this is my title", author : "bob", posted : new Date() ,
      pageViews : 5, tags : [ "fun" , "good" , "fun" ], other : { foo : 5 },
      comments : [
        { author :"joe", text : "this is cool" }, { author :"sam", text : "this is bad" }
      ]}];

  // Create a collection
  var collection = db.collection('aggregation_each_example');
  // Insert the docs
  collection.insertMany(docs, {w: 1}, function(err, result) {

    // Execute aggregate, notice the pipeline is expressed as an Array
    var cursor = collection.aggregate([
        { $project : {
          author : 1,
          tags : 1
        }},
        { $unwind : "$tags" },
        { $group : {
          _id : {tags : "$tags"},
          authors : { $addToSet : "$author" }
        }}
      ], { cursor: { batchSize: 1 } });

    // Get all the aggregation results
    cursor.each(function(err, docs) {
      test.equal(null, err);

      if(docs == null) {
        db.close();
      }
    });
  });
});

explain(callback){Promise}

Execute the explain for the cursor

Name Type Description
callback AggregationCursor~resultCallback optional

The result callback.

Returns:
Promise if no callback passed

Add a geoNear stage to the aggregation pipeline

Name Type Description
document object

The geoNear stage document.

Add a group stage to the aggregation pipeline

Name Type Description
document object

The group stage document.

hasNext(callback){Promise}

Check if there is any document still available in the cursor

Name Type Description
callback AggregationCursor~resultCallback optional

The result callback.

Throws:
Returns:
Promise if no callback passed

isClosed(){boolean}

Is the cursor closed

Add a limit stage to the aggregation pipeline

Name Type Description
value number

The state limit value.

Add a lookup stage to the aggregation pipeline

Name Type Description
document object

The lookup stage document.

Add a match stage to the aggregation pipeline

Name Type Description
document object

The match stage document.

Add a maxTimeMS stage to the aggregation pipeline

Name Type Description
value number

The state maxTimeMS value.

next(callback){Promise}

Get the next available document from the cursor, returns null if no more documents are available.

Name Type Description
callback AggregationCursor~resultCallback optional

The result callback.

Throws:
Returns:
Promise if no callback passed
Examples
// Correctly call the aggregation using a cursor and next

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Some docs for insertion
  var docs = [{
      title : "this is my title", author : "bob", posted : new Date() ,
      pageViews : 5, tags : [ "fun" , "good" , "fun" ], other : { foo : 5 },
      comments : [
        { author :"joe", text : "this is cool" }, { author :"sam", text : "this is bad" }
      ]}];

  // Create a collection
  var collection = db.collection('aggregation_next_example');
  // Insert the docs
  collection.insertMany(docs, {w: 1}, function(err, result) {

    // Execute aggregate, notice the pipeline is expressed as an Array
    var cursor = collection.aggregate([
        { $project : {
          author : 1,
          tags : 1
        }},
        { $unwind : "$tags" },
        { $group : {
          _id : {tags : "$tags"},
          authors : { $addToSet : "$author" }
        }}
      ], { cursor: { batchSize: 1 } });

    // Get all the aggregation results
    cursor.next(function(err, docs) {
      test.equal(null, err);
      db.close();
    });
  });
});
// Call next on an aggregation cursor using a Promise

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Some docs for insertion
  var docs = [{
      title : "this is my title", author : "bob", posted : new Date() ,
      pageViews : 5, tags : [ "fun" , "good" , "fun" ], other : { foo : 5 },
      comments : [
        { author :"joe", text : "this is cool" }, { author :"sam", text : "this is bad" }
      ]}];

  // Create a collection
  var collection = db.collection('aggregation_next_example_with_promise');
  // Insert the docs
  collection.insertMany(docs, {w: 1}).then(function(result) {

    // Execute aggregate, notice the pipeline is expressed as an Array
    var cursor = collection.aggregate([
        { $project : {
          author : 1,
          tags : 1
        }},
        { $unwind : "$tags" },
        { $group : {
          _id : {tags : "$tags"},
          authors : { $addToSet : "$author" }
        }}
      ], { cursor: { batchSize: 1 } });
    // Get all the aggregation results
    cursor.next().then(function(docs) {
      db.close();
    }).catch(function(err) {
      console.dir(err)
    });
  });
});
// Call next on an aggregation cursor using a Generator and the co module

var MongoClient = require('mongodb').MongoClient,
  co = require('co');
  test = require('assert');

co(function*() {
  var db = yield MongoClient.connect('mongodb://localhost:27017/test');
  // Some docs for insertion
  var docs = [{
      title : "this is my title", author : "bob", posted : new Date() ,
      pageViews : 5, tags : [ "fun" , "good" , "fun" ], other : { foo : 5 },
      comments : [
        { author :"joe", text : "this is cool" }, { author :"sam", text : "this is bad" }
      ]}];

  // Create a collection
  var collection = db.collection('aggregation_next_example_with_generatorsGenerator');

  // Insert the docs
  yield collection.insertMany(docs, {w: 1});

  // Execute aggregate, notice the pipeline is expressed as an Array
  var cursor = collection.aggregate([
      { $project : {
        author : 1,
        tags : 1
      }},
      { $unwind : "$tags" },
      { $group : {
        _id : {tags : "$tags"},
        authors : { $addToSet : "$author" }
      }}
    ], { cursor: { batchSize: 1 } });
  // Get all the aggregation results
  var doc = yield cursor.next();
  db.close();
});

Add a out stage to the aggregation pipeline

Name Type Description
destination number

The destination name.

This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer.

inherited pipe(destination, options){null}

This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream.

Name Type Description
destination Writable

The destination for writing data

options object optional

Pipe options

Add a project stage to the aggregation pipeline

Name Type Description
document object

The project stage document.

inherited read(size){String|Buffer|null}

The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null.

Name Type Description
size number

Optional argument to specify how much data to read.

Add a redact stage to the aggregation pipeline

Name Type Description
document object

The redact stage document.

This method will cause the readable stream to resume emitting data events.

Resets the cursor

inherited setEncoding(encoding){null}

Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects.

Name Type Description
encoding string

The encoding to use.

Add a skip stage to the aggregation pipeline

Name Type Description
value number

The state skip value.

Add a sort stage to the aggregation pipeline

Name Type Description
document object

The sort stage document.

toArray(callback){Promise}

Returns an array of documents. The caller is responsible for making sure that there
is enough memory to store the results. Note that the array only contain partial
results when this cursor had been previously accessed. In that case,
cursor.rewind() can be used to reset the cursor.

Name Type Description
callback AggregationCursor~toArrayResultCallback optional

The result callback.

Throws:
Returns:
Promise if no callback passed
Example
// Correctly call the aggregation using a cursor and toArray

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Some docs for insertion
  var docs = [{
      title : "this is my title", author : "bob", posted : new Date() ,
      pageViews : 5, tags : [ "fun" , "good" , "fun" ], other : { foo : 5 },
      comments : [
        { author :"joe", text : "this is cool" }, { author :"sam", text : "this is bad" }
      ]}];

  // Create a collection
  var collection = db.collection('aggregation_toArray_example');
  // Insert the docs
  collection.insertMany(docs, {w: 1}, function(err, result) {

    // Execute aggregate, notice the pipeline is expressed as an Array
    var cursor = collection.aggregate([
        { $project : {
          author : 1,
          tags : 1
        }},
        { $unwind : "$tags" },
        { $group : {
          _id : {tags : "$tags"},
          authors : { $addToSet : "$author" }
        }}
      ], { cursor: { batchSize: 1 } });

    // Get all the aggregation results
    cursor.toArray(function(err, docs) {
      test.equal(null, err);
      test.equal(2, docs.length);
      db.close();
    });
  });
});

inherited unpipe(destination){null}

This method will remove the hooks set up for a previous pipe() call.

Name Type Description
destination Writable optional

The destination for writing data

inherited unshift(chunk){null}

This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party.

Name Type Description
chunk Buffer | string

Chunk of data to unshift onto the read queue.

Add a unwind stage to the aggregation pipeline

Name Type Description
field number

The unwind field name.

inherited wrap(stream){null}

Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.)

Name Type Description
stream Stream

An "old style" readable stream.

Type Definitions

endCallback(error)

The callback error format for the forEach iterator method

Name Type Description
error MongoError

An error instance representing the error during the execution.

iteratorCallback(doc)

The callback format for the forEach iterator method

Name Type Description
doc Object

An emitted document for the iterator

resultCallback(error, result)

The callback format for results

Name Type Description
error MongoError

An error instance representing the error during the execution.

result object | null

The result object if the command was executed successfully.

toArrayResultCallback(error, documents)

The callback format for results

Name Type Description
error MongoError

An error instance representing the error during the execution.

documents Array.<object>

All the documents the satisfy the cursor.

Events

AggregationCursor stream close event

Type:
  • null

AggregationCursor stream data event, fired for each document in the cursor.

Type:
  • object

AggregationCursor stream end event

Type:
  • null

AggregationCursor stream readable event

Type:
  • null
comments powered by Disqus