Class: Cursor

Cursor

new Cursor(){Cursor}

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

Properties:
Name Type Description
sortValue string

Cursor query sort setting.

timeout boolean

Is Cursor able to time out.

readPreference ReadPreference

Get cursor ReadPreference.

cursorBatchSize number

The current cursorBatchSize for the cursor

cursorLimit number

The current cursorLimit for the cursor

cursorSkip number

The current cursorSkip for the cursor

Fires:
Returns:
Cursor instance.
Example

Some example

Extends

Methods

addCursorFlag(flag, value){Cursor}

Add a cursor flag to the cursor

Name Type Description
flag string

The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial'].

value boolean

The flag boolean value.

Throws:
MongoError

addQueryModifier(name, value){Cursor}

Add a query modifier to the cursor query

Name Type Description
name string

The query modifier (must start with $, such as $orderby etc)

value boolean

The flag boolean value.

Throws:
MongoError

batchSize(value){Cursor}

Set the batch size for the cursor.

Name Type Description
value number

The batchSize for the cursor.

Throws:
MongoError
Example
// A simple example showing the use of batchSize on the cursor, batchSize only regulates how many
// documents are returned for each batch using the getMoreCommand against the MongoDB server

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

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

  // Insert some documents we can sort on
  collection.insert([{a:1}, {a:2}, {a:3}], {w:1}, function(err, docs) {
    test.equal(null, err);

    // Do normal ascending sort
    collection.find().batchSize(1).nextObject(function(err, item) {
      test.equal(null, err);
      test.equal(1, item.a);

      db.close();
    });
  });
});

Clone the cursor

close(callback){null}

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

Name Type Description
callback Cursor~resultCallback optional

The result callback.

Example
// A simple example showing the use of the cursor close function.

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

  // Create a lot of documents to insert
  var docs = []
  for(var i = 0; i < 100; i++) {
    docs.push({'a':i})
  }

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

  // Insert documents into collection
  collection.insert(docs, {w:1}, function(err, ids) {
    // Peform a find to get a cursor
    var cursor = collection.find();

    // Fetch the first object
    cursor.nextObject(function(err, object) {
      test.equal(null, err);

      // Close the cursor, this is the same as reseting the query
      cursor.close(function(err, result) {
        test.equal(null, err);

        db.close();
      });
    });
  });
});

comment(value){Cursor}

Add a comment to the cursor query allowing for tracking the comment in the log.

Name Type Description
value string

The comment attached to this query.

Throws:
MongoError

count(applySkipLimit, readPreference, options, callback){null}

Get the count of documents for this cursor

Name Type Default Description
applySkipLimit boolean

Should the count command apply limit and skip settings on the cursor or in the passed in options.

readPreference string | ReadPreference

The new read preference for the cursor.

options object null optional

Optional settings.

Name Type Default Description
skip number null optional

The number of documents to skip.

limit number null optional

The maximum amounts to count before aborting.

maxTimeMS number null optional

Number of miliseconds to wait before aborting the query.

hint string null optional

An index name hint for the query.

callback Cursor~countResultCallback

The result callback.

Example
// A simple example showing the count function of the cursor.

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

  // Creat collection
  var collection = db.collection('cursor_count_collection');

  // Insert some docs
  collection.insert([{a:1}, {a:2}], {w:1}, function(err, docs) {
    test.equal(null, err);

    // Do a find and get the cursor count
    collection.find().count(function(err, count) {
      test.equal(null, err);
      test.equal(2, count);

      db.close();
    })
  });
});

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 previouly 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 Cursor~resultCallback

The result callback.

Deprecated
  • Yes
Throws:
MongoError
Example
// A simple example iterating over a query using the each function of the cursor.

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

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

  // Insert a document in the collection
  collection.insert({'a':1}, {w:1}, function(err, ids) {

    // Grab a cursor
    var cursor = collection.find();
    // Execute the each command, triggers for each document
    cursor.each(function(err, item) {

      // If the item is null then the cursor is exhausted/empty and closed
      if(item == null) {
        // Show that the cursor is closed
        cursor.toArray(function(err, items) {
          test.equal(null, err);

          // Let's close the db
          db.close();
        });
      };
    });
  });
});

explain(callback){null}

Execute the explain for the cursor

Name Type Description
callback Cursor~resultCallback optional

The result callback.

Example
// A simple example showing the use of the cursor explain function.

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

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

  // Insert some documents we can sort on
  collection.insert([{a:1}, {a:2}, {a:3}], {w:1}, function(err, docs) {
    test.equal(null, err);

    // Do normal ascending sort
    collection.find().explain(function(err, explaination) {
      test.equal(null, err);

      db.close();
    });
  });
});

filter(filter){Cursor}

Set the cursor query

Name Type Description
filter object

The filter object used for the cursor.

forEach(iterator, callback){null}

Iterates over all the documents for this cursor using the iterator, callback pattern.

Name Type Description
iterator Cursor~iteratorCallback

The iteration callback.

callback Cursor~endCallback

The end callback.

Throws:
MongoError
Example
// A simple example iterating over a query using the forEach function of the cursor.

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

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

  // Insert a document in the collection
  collection.insert({'a':1}, {w:1}, function(err, ids) {
    // Count of documents returned
    var count = 0;
    // Grab a cursor
    var cursor = collection.find();
    // Execute the each command, triggers for each document
    cursor.forEach(function(doc) {
      test.ok(doc != null);
      count = count + 1;
    }, function(err) {
      test.equal(null, err);
      test.equal(1, count);
      db.close();
    });
  });
});

isClosed(){boolean}

Is the cursor closed

Example
// A simple example showing the use of the cursor close function.

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

  // Create a lot of documents to insert
  var docs = []
  for(var i = 0; i < 100; i++) {
    docs.push({'a':i})
  }

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

  // Insert documents into collection
  collection.insert(docs, {w:1}, function(err, ids) {
    // Peform a find to get a cursor
    var cursor = collection.find();

    // Fetch the first object
    cursor.nextObject(function(err, object) {
      test.equal(null, err);

      // Close the cursor, this is the same as reseting the query
      cursor.close(function(err, result) {
        test.equal(null, err);
        test.equal(true, cursor.isClosed());

        db.close();
      });
    });
  });
});

limit(value){Cursor}

Set the limit for the cursor.

Name Type Description
value number

The limit for the cursor query.

Throws:
MongoError
Example
// A simple example showing the use of limit on the cursor

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

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

  // Insert some documents we can sort on
  collection.insert([{a:1}, {a:2}, {a:3}], {w:1}, function(err, docs) {
    test.equal(null, err);

    // Limit to only one document returned
    collection.find().limit(1).toArray(function(err, items) {
      test.equal(null, err);
      test.equal(1, items.length);

      db.close();
    });
  });
});

maxTimeMS(value){Cursor}

Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher)

Name Type Description
value number

Number of milliseconds to wait before aborting the query.

Throws:
MongoError

inherited next(callback){null}

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

Name Type Description
callback Cursor~resultCallback

The result callback.

Throws:
MongoError

nextObject(callback){null}

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

Name Type Description
callback Cursor~resultCallback

The result callback.

Deprecated
  • Yes
Throws:
MongoError
Example
// A simple example showing the use of nextObject.

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

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

  // Insert some documents we can sort on
  collection.insert([{a:1}, {a:2}, {a:3}], {w:1}, function(err, docs) {
    test.equal(null, err);

    // Do normal ascending sort
    collection.find().nextObject(function(err, item) {
      test.equal(null, err);
      test.equal(1, item.a);

      db.close();
    });
  });
});

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

project(value){Cursor}

Sets a field projection for the query.

Name Type Description
value object

The field projection object.

Throws:
MongoError

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.

inherited resume(){null}

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

inherited rewind(){null}

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.

setReadPreference(readPreference){Cursor}

Set the ReadPreference for the cursor.

Name Type Description
readPreference string | ReadPreference

The new read preference for the cursor.

Throws:
MongoError

skip(value){Cursor}

Set the skip for the cursor.

Name Type Description
value number

The skip for the cursor query.

Throws:
MongoError
Example
// A simple example showing the use of skip on the cursor

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

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

  // Insert some documents we can sort on
  collection.insert([{a:1}, {a:2}, {a:3}], {w:1}, function(err, docs) {
    test.equal(null, err);

    // Skip one document
    collection.find().skip(1).nextObject(function(err, item) {
      test.equal(null, err);
      test.equal(2, item.a);

      db.close();
    });
  });
});

sort(keyOrList, direction){Cursor}

Sets the sort order of the cursor query.

Name Type Description
keyOrList string | array | object

The key or keys set for the sort.

direction number optional

The direction of the sorting (1 or -1).

Throws:
MongoError
Example
// A simple example showing the use of sort on the cursor.

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

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

  // Insert some documents we can sort on
  collection.insert([{a:1}, {a:2}, {a:3}], {w:1}, function(err, docs) {
    test.equal(null, err);

    // Do normal ascending sort
    collection.find().sort([['a', 1]]).nextObject(function(err, item) {
      test.equal(null, err);
      test.equal(1, item.a);

      // Do normal descending sort
      collection.find().sort([['a', -1]]).nextObject(function(err, item) {
        test.equal(null, err);
        test.equal(3, item.a);

        db.close();
      });
    });
  });
});

stream(options){Cursor}

Return a modified Readable stream including a possible transform method.

Name Type Default Description
options object null optional

Optional settings.

Name Type Default Description
transform function null optional

A transformation method applied to each document emitted by the stream.

Examples
// A simple example showing the use of the cursor stream function.

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

  // Create a lot of documents to insert
  var docs = []
  for(var i = 0; i < 100; i++) {
    docs.push({'a':i})
  }

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

  // Insert documents into collection
  collection.insert(docs, {w:1}, function(err, ids) {
    // Peform a find to get a cursor
    var stream = collection.find().stream();

    // Execute find on all the documents
    stream.on('end', function() {
      db.close();
    });

    stream.on('data', function(data) {
      test.ok(data != null);
    });
  });
});
// A simple example showing the use of the cursorstream pause function.

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

  // Create a lot of documents to insert
  var docs = []
  var fetchedDocs = [];
  for(var i = 0; i < 2; i++) {
    docs.push({'a':i})
  }

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

  // Insert documents into collection
  collection.insert(docs, {w:1}, function(err, ids) {
    // Peform a find to get a cursor
    var stream = collection.find().stream();

    // For each data item
    stream.on("data", function(item) {
      fetchedDocs.push(item)
      // Pause stream
      stream.pause();

      // Restart the stream after 1 miliscecond
      setTimeout(function() {
        fetchedDocs.push(null);
        stream.resume();
      }, 1);
    });

    // When the stream is done
    stream.on("end", function() {
      test.equal(null, fetchedDocs[1]);
      db.close();
    });
  });
});

toArray(callback){null}

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 previouly accessed. In that case, cursor.rewind() can be used to reset the cursor.

Name Type Description
callback Cursor~toArrayResultCallback

The result callback.

Throws:
MongoError
Example
// An example showing the information returned by indexInformation

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

  // Create a collection to hold our documents
  var collection = db.collection('test_array');

  // Insert a test document
  collection.insert({'b':[1, 2, 3]}, {w:1}, function(err, ids) {

    // Retrieve all the documents in the collection
    collection.find().toArray(function(err, documents) {
      test.equal(1, documents.length);
      test.deepEqual([1, 2, 3], documents[0].b);

      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.

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

countResultCallback(error, count)

The callback format for results

Name Type Description
error MongoError

An error instance representing the error during the execution.

count number

The count of documents.

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

Cursor stream close event

Type:
  • null

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

Type:
  • object

Cursor stream end event

Type:
  • null

Cursor stream readable event

Type:
  • null
comments powered by Disqus
Documentation generated by JSDoc 3.3.0-alpha9 on Wed Oct 29 2014 13:10:23 GMT+0100 (CET)