Class: Collection

Collection

new Collection(){Collection}

Create a new Collection instance (INTERNAL TYPE, do not instantiate directly)

Properties:
Name Type Description
collectionName string

Get the collection name.

namespace string

Get the full collection namespace.

writeConcern object

The current write concern values.

readConcern object

The current read concern values.

hint object

Get current index hint for collection.

Returns:
Collection instance.

Methods

aggregate(pipeline, options, callback){null|AggregationCursor}

Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2

Name Type Default Description
pipeline object

Array containing all the aggregation framework commands for the execution.

options object null optional

Optional settings.

Name Type Default Description
readPreference ReadPreference | string null optional

The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).

cursor object null optional

Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor.

Name Type Default Description
batchSize number null optional

The batchSize for the cursor

explain boolean false optional

Explain returns the aggregation execution plan (requires mongodb 2.6 >).

allowDiskUse boolean false optional

allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >).

maxTimeMS number null optional

maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point.

bypassDocumentValidation boolean false optional

Allow driver to bypass schema validation in MongoDB 3.2 or higher.

raw boolean false optional

Return document results as raw BSON buffers.

promoteLongs boolean true optional

Promotes Long values to number if they fit inside the 53 bits resolution.

promoteValues boolean true optional

Promotes BSON values to native types where possible, set to false to only receive wrapper types.

promoteBuffers boolean false optional

Promotes Binary BSON values to native Node Buffers.

collation object null optional

Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).

callback Collection~resultCallback

The command result callback

Examples
// Correctly call the aggregation framework using a pipeline in an Array.

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('aggregationExample1');
  // Insert the docs
  collection.insertMany(docs, {w: 1}, function(err, result) {

    // Execute aggregate, notice the pipeline is expressed as an Array
    collection.aggregate([
        { $project : {
          author : 1,
          tags : 1
        }},
        { $unwind : "$tags" },
        { $group : {
          _id : {tags : "$tags"},
          authors : { $addToSet : "$author" }
        }}
      ], function(err, result) {
        test.equal(null, err);
        test.equal('good', result[0]._id.tags);
        test.deepEqual(['bob'], result[0].authors);
        test.equal('fun', result[1]._id.tags);
        test.deepEqual(['bob'], result[1].authors);

        db.close();
    });
  });
});
// Correctly call the aggregation using a cursor

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('aggregationExample2');
  // 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();
    });
  });
});
// Correctly call the aggregation using a read stream

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('aggregationExample3');
  // 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 } });

    var count = 0;
    // Get all the aggregation results
    cursor.on('data', function(doc) {
      count = count + 1;
    });

    cursor.once('end', function() {
      test.equal(2, count);
      db.close();
    });
  });
});
// Call toArray 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('aggregationExample2_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.toArray().then(function(docs) {
      test.equal(2, docs.length);
      db.close();
    }).catch(function(err) {
      console.log(err.stack);
    });
  });
});
// Call toArray on an aggregation cursor using ES6 generators 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('aggregationExample2_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 docs = yield cursor.toArray();
  test.equal(2, docs.length);
  db.close();
});

bulkWrite(operations, options, callback){Promise}

Perform a bulkWrite operation without a fluent API

Legal operation types are

{ insertOne: { document: { a: 1 } } }

{ updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }

{ updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }

{ deleteOne: { filter: {c:1} } }

{ deleteMany: { filter: {c:1} } }

{ replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}}

If documents passed in do not contain the _id field,
one will be added to each of the documents missing it by the driver, mutating the document. This behavior
can be overridden by setting the forceServerObjectId flag.

Name Type Default Description
operations Array.<object>

Bulk operations to perform.

options object null optional

Optional settings.

Name Type Default Description
w number | string null optional

The write concern.

wtimeout number null optional

The write concern timeout.

j boolean false optional

Specify a journal write concern.

serializeFunctions boolean false optional

Serialize functions on any object.

ordered boolean true optional

Execute write operation in ordered or unordered fashion.

bypassDocumentValidation boolean false optional

Allow driver to bypass schema validation in MongoDB 3.2 or higher.

callback Collection~bulkWriteOpCallback optional

The command result callback

Returns:
Promise if no callback passed
Examples
// Example of a simple bulkWrite operation

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Get the collection
  var col = db.collection('bulk_write');
  col.bulkWrite([
      { insertOne: { document: { a: 1 } } }
    , { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
    , { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
    , { deleteOne: { filter: {c:1} } }
    , { deleteMany: { filter: {c:1} } }
    , { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}}]
  , {ordered:true, w:1}, function(err, r) {
    test.equal(null, err);
    test.equal(1, r.nInserted);
    test.equal(2, r.nUpserted);
    test.equal(0, r.nRemoved);

    // Crud fields
    test.equal(1, r.insertedCount);
    test.equal(1, Object.keys(r.insertedIds).length);
    test.equal(1, r.matchedCount);
    test.ok(r.modifiedCount == 0 || r.modifiedCount == 1);
    test.equal(0, r.deletedCount);
    test.equal(2, r.upsertedCount);
    test.equal(2, Object.keys(r.upsertedIds).length);

    // Ordered bulk operation
    db.close();
  });
});
// Example of a simple bulkWrite operation using a Promise.

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Get the collection
  var col = db.collection('bulk_write_with_promise');
  col.bulkWrite([
      { insertOne: { document: { a: 1 } } }
    , { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
    , { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
    , { deleteOne: { filter: {c:1} } }
    , { deleteMany: { filter: {c:1} } }
    , { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}}]
  , {ordered:true, w:1}).then(function(r) {
    // console.log(JSON.stringify(r, null, 2))
    test.equal(1, r.nInserted);
    test.equal(2, r.nUpserted);
    test.equal(0, r.nRemoved);
    // Crud fields
    test.equal(1, r.insertedCount);
    test.equal(1, Object.keys(r.insertedIds).length);
    test.equal(1, r.matchedCount);
    test.ok(r.modifiedCount == 0 || r.modifiedCount == 1);
    test.equal(0, r.deletedCount);
    test.equal(2, r.upsertedCount);
    test.equal(2, Object.keys(r.upsertedIds).length);

    // Ordered bulk operation
    db.close();
  });
});
// Example of a simple bulkWrite operation 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');
  // Get the collection
  var col = db.collection('bulk_write_with_generators');
  var r = yield col.bulkWrite([
      { insertOne: { document: { a: 1 } } }
    , { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
    , { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
    , { deleteOne: { filter: {c:1} } }
    , { deleteMany: { filter: {c:1} } }
    , { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}}]
  , {ordered:true, w:1});
  test.equal(1, r.nInserted);
  test.equal(2, r.nUpserted);
  test.equal(0, r.nRemoved);

  // Crud fields
  test.equal(1, r.insertedCount);
  test.equal(1, Object.keys(r.insertedIds).length);
  test.equal(1, r.matchedCount);
  test.ok(r.modifiedCount == 0 || r.modifiedCount == 1);
  test.equal(0, r.deletedCount);
  test.equal(2, r.upsertedCount);
  test.equal(2, Object.keys(r.upsertedIds).length);

  // Ordered bulk operation
  db.close();
});

count(query, options, callback){Promise}

Count number of matching documents in the db to a query.

Name Type Default Description
query object

The query for the count.

options object null optional

Optional settings.

Name Type Default Description
limit boolean null optional

The limit of documents to count.

skip boolean null optional

The number of documents to skip for the count.

hint string null optional

An index name hint for the query.

readPreference ReadPreference | string null optional

The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).

maxTimeMS number null optional

Number of milliseconds to wait before aborting the query.

callback Collection~countCallback optional

The command result callback

Returns:
Promise if no callback passed
Examples
// Example of running simple count commands against a collection.

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Crete the collection for the distinct example
  var collection = db.collection('countExample1');
  // Insert documents to perform distinct against
  collection.insertMany([{a:1}, {a:2}
    , {a:3}, {a:4, b:1}], {w: 1}, function(err, ids) {

    // Perform a total count command
    collection.count(function(err, count) {
      test.equal(null, err);
      test.equal(4, count);

      // Perform a partial account where b=1
      collection.count({b:1}, function(err, count) {
        test.equal(null, err);
        test.equal(1, count);

        db.close();
      });
    });
  });
});
// Example of running simple count commands against a collection using a Promise.

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Crete the collection for the distinct example
  var collection = db.collection('countExample1_with_promise');
  // Insert documents to perform distinct against
  collection.insertMany([{a:1}, {a:2}
    , {a:3}, {a:4, b:1}], {w: 1}).then(function(ids) {
    // Perform a total count command
    collection.count().then(function(count) {
      test.equal(4, count);

      // Perform a partial account where b=1
      collection.count({b:1}).then(function(count) {
        test.equal(1, count);

        db.close();
      });
    });
  });
});
// Example of running simple count commands against a collection 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');
  // Crete the collection for the distinct example
  var collection = db.collection('countExample1_with_generators');
  // Insert documents to perform distinct against
  var result = yield collection.insertMany([{a:1}, {a:2}
    , {a:3}, {a:4, b:1}], {w: 1});
  // Perform a total count command
  var count = yield collection.count();
  test.equal(4, count);

  // Perform a partial account where b=1
  var count = yield collection.count({b:1});
  test.equal(1, count);

  // Close database
  db.close();
});

createIndex(fieldOrSpec, options, callback){Promise}

Creates an index on the db and collection collection.

Name Type Default Description
fieldOrSpec string | object

Defines the index.

options object null optional

Optional settings.

Name Type Default Description
w number | string null optional

The write concern.

wtimeout number null optional

The write concern timeout.

j boolean false optional

Specify a journal write concern.

unique boolean false optional

Creates an unique index.

sparse boolean false optional

Creates a sparse index.

background boolean false optional

Creates the index in the background, yielding whenever possible.

dropDups boolean false optional

A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value

min number null optional

For geospatial indexes set the lower bound for the co-ordinates.

max number null optional

For geospatial indexes set the high bound for the co-ordinates.

v number null optional

Specify the format version of the indexes.

expireAfterSeconds number null optional

Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)

name string null optional

Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)

partialFilterExpression object null optional

Creates a partial index based on the given filter object (MongoDB 3.2 or higher)

collation object null optional

Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).

callback Collection~resultCallback optional

The command result callback

Returns:
Promise if no callback passed
Examples
// A more complex createIndex using a compound unique index in the background and dropping duplicated documents

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Create a collection we want to drop later
  var collection = db.collection('createIndexExample1');
  // Insert a bunch of documents for the index
  collection.insertMany([{a:1, b:1}
    , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}, function(err, result) {
    test.equal(null, err);

    // Create an index on the a field
    collection.createIndex({a:1, b:1}
      , {unique:true, background:true, w:1}, function(err, indexName) {

      // Show that duplicate records got dropped
      collection.find({}).toArray(function(err, items) {
        test.equal(null, err);
        test.equal(4, items.length);

        // Perform a query, with explain to show we hit the query
        collection.find({a:2}).explain(function(err, explanation) {
          test.equal(null, err);
          test.ok(explanation != null);

          db.close();
        });
      })
    });
  });
});
// A simple createIndex using a simple single field index

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

  // Create a collection we want to drop later
  var collection = db.collection('createIndexExample2');
  // Insert a bunch of documents for the index
  collection.insertMany([{a:1}, {a:2}, {a:3}, {a:4}], {w:1}, function(err, result) {
    test.equal(null, err);

    // Create an index on the a field
    collection.createIndex('a', {w:1}, function(err, indexName) {
      test.equal("a_1", indexName);

      // Perform a query, with explain to show we hit the query
      collection.find({a:2}).explain(function(err, explanation) {
        test.equal(null, err);
        test.ok(explanation != null);

        db.close();
      });
    });
  });
});
// A more complex createIndex using a compound unique index in the background

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

  // Create a collection we want to drop later
  var collection = db.collection('createIndexExample3');
  // Insert a bunch of documents for the index
  collection.insertMany([{a:1, b:1}
    , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}, function(err, result) {
    test.equal(null, err);

    var options = {unique:true, background:true, w:1};
    // Create an index on the a field
    collection.createIndex({a:1, b:1}
      , options, function(err, indexName) {

      test.ok(!options.readPreference);
      // Show that duplicate records got dropped
      collection.find({}).toArray(function(err, items) {
        test.equal(null, err);
        test.equal(4, items.length);

        // Perform a query, with explain to show we hit the query
        collection.find({a:2}).explain(function(err, explanation) {
          test.equal(null, err);
          test.ok(explanation != null);

          db.close();
        });
      })
    });
  });
});
// A more complex createIndex using a Promise and a compound unique index in the background and dropping duplicated documents

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Create a collection we want to drop later
  var collection = db.collection('createIndexExample1_with_promise');
  // Insert a bunch of documents for the index
  collection.insertMany([{a:1, b:1}
    , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}).then(function(result) {

    // Create an index on the a field
    collection.createIndex({a:1, b:1}
      , {unique:true, background:true, w:1}).then(function(indexName) {

      // Show that duplicate records got dropped
      collection.find({}).toArray().then(function(items) {
        test.equal(4, items.length);

        // Perform a query, with explain to show we hit the query
        collection.find({a:2}).explain().then(function(explanation) {
          test.ok(explanation != null);

          db.close();
        });
      })
    });
  });
});
// A more complex createIndex using a Generator and the co module and a compound unique index in the background and dropping duplicated documents

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

co(function*() {
  var db = yield MongoClient.connect('mongodb://localhost:27017/test');
  // Create a collection we want to drop later
  var collection = db.collection('createIndexExample1_with_generators');
  // Insert a bunch of documents for the index
  yield collection.insertMany([{a:1, b:1}
    , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1});

  // Create an index on the a field
  yield collection.createIndex({a:1, b:1}
    , {unique:true, background:true, w:1});

  // Show that duplicate records got dropped
  var items = yield collection.find({}).toArray();
  test.equal(4, items.length);

  // Perform a query, with explain to show we hit the query
  var explanation = yield collection.find({a:2}).explain()
  test.ok(explanation != null);

  db.close();
});

createIndexes(indexSpecs, callback){Promise}

Creates multiple indexes in the collection, this method is only supported for
MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported
error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/.

Name Type Description
indexSpecs array

An array of index specifications to be created

callback Collection~resultCallback optional

The command result callback

Returns:
Promise if no callback passed

deleteMany(filter, options, callback){Promise}

Delete multiple documents on MongoDB

Name Type Default Description
filter object

The Filter used to select the documents to remove

options object null optional

Optional settings.

Name Type Default Description
w number | string null optional

The write concern.

wtimeout number null optional

The write concern timeout.

j boolean false optional

Specify a journal write concern.

callback Collection~deleteWriteOpCallback optional

The command result callback

Returns:
Promise if no callback passed

deleteOne(filter, options, callback){Promise}

Delete a document on MongoDB

Name Type Default Description
filter object

The Filter used to select the document to remove

options object null optional

Optional settings.

Name Type Default Description
w number | string null optional

The write concern.

wtimeout number null optional

The write concern timeout.

j boolean false optional

Specify a journal write concern.

callback Collection~deleteWriteOpCallback optional

The command result callback

Returns:
Promise if no callback passed

distinct(key, query, options, callback){Promise}

The distinct command returns returns a list of distinct values for the given key across a collection.

Name Type Default Description
key string

Field of the document to find distinct values for.

query object

The query for filtering the set of documents to which we apply the distinct filter.

options object null optional

Optional settings.

Name Type Default Description
readPreference ReadPreference | string null optional

The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).

maxTimeMS number null optional

Number of milliseconds to wait before aborting the query.

callback Collection~resultCallback optional

The command result callback

Returns:
Promise if no callback passed
Examples
// Example of running the distinct command against a collection

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Crete the collection for the distinct example
  var collection = db.collection('distinctExample1');

  // Insert documents to perform distinct against
  collection.insertMany([{a:0, b:{c:'a'}}, {a:1, b:{c:'b'}}, {a:1, b:{c:'c'}},
    {a:2, b:{c:'a'}}, {a:3}, {a:3}], {w:1}, function(err, ids) {

    // Perform a distinct query against the a field
    collection.distinct('a', function(err, docs) {
      test.deepEqual([0, 1, 2, 3], docs.sort());

      // Perform a distinct query against the sub-field b.c
      collection.distinct('b.c', function(err, docs) {
        test.deepEqual(['a', 'b', 'c'], docs.sort());

        db.close();
      });
    });
  });
});
// Example of running the distinct command against a collection with a filter query

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

  // Crete the collection for the distinct example
  var collection = db.collection('distinctExample2');

  // Insert documents to perform distinct against
  collection.insertMany([{a:0, b:{c:'a'}}, {a:1, b:{c:'b'}}, {a:1, b:{c:'c'}},
    {a:2, b:{c:'a'}}, {a:3}, {a:3}, {a:5, c:1}], {w:1}, function(err, ids) {

    // Perform a distinct query with a filter against the documents
    collection.distinct('a', {c:1}, function(err, docs) {
      test.deepEqual([5], docs.sort());

      db.close();
    });
  })
});
// Example of running the distinct command using a Promise against a collection

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Crete the collection for the distinct example
  var collection = db.collection('distinctExample1_with_promise');

  // Insert documents to perform distinct against
  collection.insertMany([{a:0, b:{c:'a'}}, {a:1, b:{c:'b'}}, {a:1, b:{c:'c'}},
    {a:2, b:{c:'a'}}, {a:3}, {a:3}], {w:1}).then(function(ids) {

    // Perform a distinct query against the a field
    collection.distinct('a').then(function(docs) {
      test.deepEqual([0, 1, 2, 3], docs.sort());

      // Perform a distinct query against the sub-field b.c
      collection.distinct('b.c').then(function(docs) {
        test.deepEqual(['a', 'b', 'c'], docs.sort());

        db.close();
      });
    });
  });
});
// Example of running the distinct command using a Generator and the co module against a collection

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

co(function*() {
  var db = yield MongoClient.connect('mongodb://localhost:27017/test');
  // Crete the collection for the distinct example
  var collection = db.collection('distinctExample1_with_generators');

  // Insert documents to perform distinct against
  yield collection.insertMany([{a:0, b:{c:'a'}}, {a:1, b:{c:'b'}}, {a:1, b:{c:'c'}},
    {a:2, b:{c:'a'}}, {a:3}, {a:3}], {w:1});

  // Perform a distinct query against the a field
  var docs = yield collection.distinct('a');
  test.deepEqual([0, 1, 2, 3], docs.sort());

  // Perform a distinct query against the sub-field b.c
  var docs = yield collection.distinct('b.c');
  test.deepEqual(['a', 'b', 'c'], docs.sort());

  db.close();
});

drop(options, callback){Promise}

Drop the collection from the database, removing it permanently. New accesses will create a new collection.

Name Type Default Description
options object null optional

Optional settings.

callback Collection~resultCallback optional

The results callback

Returns:
Promise if no callback passed
Examples
// Example of a simple collection drop.

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

  // Create a collection we want to drop later
  var collection = db.collection('test_other_drop');

  // Drop the collection
  collection.drop(function(err, reply) {

    // Ensure we don't have the collection in the set of names
    db.listCollections().toArray(function(err, replies) {

      var found = false;
      // For each collection in the list of collection names in this db look for the
      // dropped collection
      replies.forEach(function(document) {
        if(document.name == "test_other_drop") {
          found = true;
          return;
        }
      });

      // Ensure the collection is not found
      test.equal(false, found);

      // Let's close the db
      db.close();
    });
  });
});
// Example of Collection.prototype.drop using a Promise

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

  // Create a collection we want to drop later
  db.createCollection('test_other_drop_with_promise').then(function(collection) {
    // Drop the collection
    collection.drop().then(function(reply) {

      // Ensure we don't have the collection in the set of names
      db.listCollections().toArray().then(function(replies) {

        var found = false;
        // For each collection in the list of collection names in this db look for the
        // dropped collection
        replies.forEach(function(document) {
          if(document.name == "test_other_drop_with_promise") {
            found = true;
            return;
          }
        });

        // Ensure the collection is not found
        test.equal(false, found);

        // Let's close the db
        db.close();
      });
    });
  });
});
// Example of Collection.prototype.drop 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');

  // Create a collection we want to drop later
  var collection = yield db.createCollection('test_other_drop_with_generators');

  // Drop the collection
  yield collection.drop();

  // Ensure we don't have the collection in the set of names
  var replies = yield db.listCollections().toArray();

  // Did we find the collection
  var found = false;
  // For each collection in the list of collection names in this db look for the
  // dropped collection
  replies.forEach(function(document) {
    if(document.name == "test_other_drop_with_generators") {
      found = true;
      return;
    }
  });

  // Ensure the collection is not found
  test.equal(false, found);

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

dropAllIndexes(callback){Promise}

Drops all indexes from this collection.

Name Type Description
callback Collection~resultCallback

The command result callback

Deprecated
  • use dropIndexes
    Returns:
    Promise if no [callback] passed
    Examples
    // Example of a how to drop all the indexes on a collection using dropAllIndexes
    
    var MongoClient = require('mongodb').MongoClient,
      test = require('assert');
    MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
      db.createCollection('dropExample1', function(err, r) {
        test.equal(null, err);
    
        // Drop the collection
        db.collection('dropExample1').dropAllIndexes(function(err, reply) {
          test.equal(null, err);
    
          // Let's close the db
          db.close();
        });
      });
    });
    // Example of a how to drop all the indexes on a collection using dropAllIndexes with a Promise
    
    var MongoClient = require('mongodb').MongoClient,
      test = require('assert');
    MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
      db.createCollection('dropExample1_with_promise').then(function(r) {
        // Drop the collection
        db.collection('dropExample1_with_promise').dropAllIndexes().then(function(reply) {
          // Let's close the db
          db.close();
        });
      });
    });
    // Example of a how to drop all the indexes on a collection using dropAllIndexes with 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');
      yield db.createCollection('dropExample1_with_generators');
      // Drop the collection
      yield db.collection('dropExample1_with_generators').dropAllIndexes();
      // Let's close the db
      db.close();
    });

    dropIndex(indexName, options, callback){Promise}

    Drops an index from this collection.

    Name Type Default Description
    indexName string

    Name of the index to drop.

    options object null optional

    Optional settings.

    Name Type Default Description
    w number | string null optional

    The write concern.

    wtimeout number null optional

    The write concern timeout.

    j boolean false optional

    Specify a journal write concern.

    callback Collection~resultCallback optional

    The command result callback

    Returns:
    Promise if no callback passed
    Examples
    // An examples showing the creation and dropping of an index
    
    var MongoClient = require('mongodb').MongoClient,
      test = require('assert');
    MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
      var collection = db.collection('dropIndexExample1');
      // Insert a bunch of documents for the index
      collection.insertMany([{a:1, b:1}
        , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}, function(err, result) {
        test.equal(null, err);
    
        // Create an index on the a field
        collection.ensureIndex({a:1, b:1}
          , {unique:true, background:true, w:1}, function(err, indexName) {
    
          // Drop the index
          collection.dropIndex("a_1_b_1", function(err, result) {
            test.equal(null, err);
    
            // Verify that the index is gone
            collection.indexInformation(function(err, indexInformation) {
              test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_);
              test.equal(null, indexInformation.a_1_b_1);
    
              db.close();
            });
          });
        });
      });
    });
    // An examples showing the creation and dropping of an index using a Promise
    
    var MongoClient = require('mongodb').MongoClient,
      test = require('assert');
    MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
      var collection = db.collection('dropIndexExample1_with_promise');
      // Insert a bunch of documents for the index
      collection.insertMany([{a:1, b:1}
        , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}).then(function(result) {
    
        // Create an index on the a field
        collection.ensureIndex({a:1, b:1}
          , {unique:true, background:true, w:1}).then(function(indexName) {
    
          // Drop the index
          collection.dropIndex("a_1_b_1").then(function(result) {
    
            // Verify that the index is gone
            collection.indexInformation().then(function(indexInformation) {
              test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_);
              test.equal(null, indexInformation.a_1_b_1);
    
              db.close();
            });
          });
        });
      });
    });
    // An examples showing the creation and dropping of an index 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');
      var collection = db.collection('dropIndexExample1_with_generators');
      // Insert a bunch of documents for the index
      yield collection.insertMany([{a:1, b:1}
        , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1});
    
      // Create an index on the a field
      yield collection.ensureIndex({a:1, b:1}
        , {unique:true, background:true, w:1});
    
      // Drop the index
      yield collection.dropIndex("a_1_b_1");
    
      // Verify that the index is gone
      var indexInformation = yield collection.indexInformation()
      test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_);
      test.equal(null, indexInformation.a_1_b_1);
    
      // Close db
      db.close();
    });

    dropIndexes(callback){Promise}

    Drops all indexes from this collection.

    Name Type Description
    callback Collection~resultCallback optional

    The command result callback

    Returns:
    Promise if no callback passed
    Examples
    // An examples showing the creation and dropping of an index
    
    var MongoClient = require('mongodb').MongoClient,
      test = require('assert');
    MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
    
      // Create a collection we want to drop later
      var collection = db.collection('shouldCorrectlyCreateAndDropAllIndex');
      // Insert a bunch of documents for the index
      collection.insertMany([{a:1, b:1}
        , {a:2, b:2}, {a:3, b:3}, {a:4, b:4, c:4}], {w:1}, function(err, result) {
        test.equal(null, err);
    
        // Create an index on the a field
        collection.ensureIndex({a:1, b:1}
          , {unique:true, background:true, w:1}, function(err, indexName) {
    
          // Create an additional index
          collection.ensureIndex({c:1}
            , {unique:true, background:true, w:1}, function(err, indexName) {
    
            // Drop the index
            collection.dropAllIndexes(function(err, result) {
              test.equal(null, err);
    
              // Verify that the index is gone
              collection.indexInformation(function(err, indexInformation) {
                test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_);
                test.equal(null, indexInformation.a_1_b_1);
                test.equal(null, indexInformation.c_1);
    
                db.close();
              });
            });
          });
        });
      });
    });
    // An examples showing the creation and dropping of an index using Promises.
    
    var MongoClient = require('mongodb').MongoClient,
      test = require('assert');
    MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
    
      // Create a collection we want to drop later
      var collection = db.collection('shouldCorrectlyCreateAndDropAllIndex_with_promise');
      // Insert a bunch of documents for the index
      collection.insertMany([{a:1, b:1}
        , {a:2, b:2}, {a:3, b:3}, {a:4, b:4, c:4}], {w:1}).then(function(result) {
    
        // Create an index on the a field
        collection.ensureIndex({a:1, b:1}
          , {unique:true, background:true, w:1}).then(function(indexName) {
    
          // Create an additional index
          collection.ensureIndex({c:1}
            , {unique:true, background:true, sparse:true, w:1}).then(function(indexName) {
    
            // Drop the index
            collection.dropAllIndexes().then(function(result) {
    
              // Verify that the index is gone
              collection.indexInformation().then(function(indexInformation) {
                test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_);
                test.equal(null, indexInformation.a_1_b_1);
                test.equal(null, indexInformation.c_1);
    
                db.close();
              });
            });
          });
        });
      });
    });
    // An examples showing the creation and dropping of an index using Generators.
    
    var MongoClient = require('mongodb').MongoClient,
      co = require('co');
      test = require('assert');
    
    co(function*() {
      var db = yield MongoClient.connect('mongodb://localhost:27017/test');
    
      // Create a collection we want to drop later
      var collection = db.collection('shouldCorrectlyCreateAndDropAllIndex_with_generators');
      // Insert a bunch of documents for the index
      yield collection.insertMany([{a:1, b:1}
        , {a:2, b:2}, {a:3, b:3}, {a:4, b:4, c:4}], {w:1});
    
      // Create an index on the a field
      yield collection.ensureIndex({a:1, b:1}
        , {unique:true, background:true, w:1});
    
      // Create an additional index
      yield collection.ensureIndex({c:1}
        , {unique:true, background:true, sparse:true, w:1});
    
      // Drop the index
      yield collection.dropAllIndexes();
    
      // Verify that the index is gone
      var indexInformation = yield collection.indexInformation();
      test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_);
      test.equal(null, indexInformation.a_1_b_1);
      test.equal(null, indexInformation.c_1);
    
      db.close();
    });

    ensureIndex(fieldOrSpec, options, callback){Promise}

    Ensures that an index exists, if it does not it creates it

    Name Type Default Description
    fieldOrSpec string | object

    Defines the index.

    options object null optional

    Optional settings.

    Name Type Default Description
    w number | string null optional

    The write concern.

    wtimeout number null optional

    The write concern timeout.

    j boolean false optional

    Specify a journal write concern.

    unique boolean false optional

    Creates an unique index.

    sparse boolean false optional

    Creates a sparse index.

    background boolean false optional

    Creates the index in the background, yielding whenever possible.

    dropDups boolean false optional

    A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value

    min number null optional

    For geospatial indexes set the lower bound for the co-ordinates.

    max number null optional

    For geospatial indexes set the high bound for the co-ordinates.

    v number null optional

    Specify the format version of the indexes.

    expireAfterSeconds number null optional

    Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)

    name number null optional

    Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)

    collation object null optional

    Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).

    callback Collection~resultCallback optional

    The command result callback

    Deprecated
    • use createIndexes instead
      Returns:
      Promise if no callback passed
      Examples
      // A more complex ensureIndex using a compound unique index in the background and dropping duplicated documents.
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
        var collection = db.collection('ensureIndexExample1');
        // Insert a bunch of documents for the index
        collection.insertMany([{a:1, b:1}
          , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}, function(err, result) {
          test.equal(null, err);
      
          // Create an index on the a field
          db.ensureIndex('ensureIndexExample1', {a:1, b:1}
            , {unique:true, background:true, w:1}, function(err, indexName) {
      
            // Show that duplicate records got dropped
            collection.find({}).toArray(function(err, items) {
              test.equal(null, err);
              test.equal(4, items.length);
      
              // Perform a query, with explain to show we hit the query
              collection.find({a:2}).explain(function(err, explanation) {
                test.equal(null, err);
                test.ok(explanation != null);
      
                db.close();
              });
            })
          });
        });
      });
      // A more complex ensureIndex using a compound unique index in the background.
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
        var collection = db.collection('ensureIndexExample2');
        // Insert a bunch of documents for the index
        collection.insertMany([{a:1, b:1}
          , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}, function(err, result) {
          test.equal(null, err);
      
          // Create an index on the a field
          collection.ensureIndex({a:1, b:1}
            , {unique:true, background:true, w:1}, function(err, indexName) {
            test.equal(null, err);
      
            // Show that duplicate records got dropped
            collection.find({}).toArray(function(err, items) {
              test.equal(null, err);
              test.equal(4, items.length);
      
              // Perform a query, with explain to show we hit the query
              collection.find({a:2}).explain(function(err, explanation) {
                test.equal(null, err);
                test.ok(explanation != null);
      
                db.close();
              });
            })
          });
        });
      });
      // A more complex ensureIndex using a compound unique index in the background and dropping duplicated documents using a Promise.
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
        var collection = db.collection('ensureIndexExample1_with_promise');
        // Insert a bunch of documents for the index
        collection.insertMany([{a:1, b:1}
          , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}).then(function(result) {
      
          // Create an index on the a field
          db.ensureIndex('ensureIndexExample1_with_promise', {a:1, b:1}
            , {unique:true, background:true, w:1}).then(function(indexName) {
      
            // Show that duplicate records got dropped
            collection.find({}).toArray().then(function(items) {
              test.equal(4, items.length);
      
              // Perform a query, with explain to show we hit the query
              collection.find({a:2}).explain().then(function(explanation) {
                test.ok(explanation != null);
      
                db.close();
              });
            })
          });
        });
      });
      // A more complex ensureIndex using a compound unique index in the background using a Promise.
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
        var collection = db.collection('ensureIndexExample2_with_promise');
        // Insert a bunch of documents for the index
        collection.insertMany([{a:1, b:1}
          , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}).then(function(result) {
      
          // Create an index on the a field
          collection.ensureIndex({a:1, b:1}
            , {unique:true, background:true, w:1}).then(function(indexName) {
      
            // Show that duplicate records got dropped
            collection.find({}).toArray().then(function(items) {
              test.equal(4, items.length);
      
              // Perform a query, with explain to show we hit the query
              collection.find({a:2}).explain().then(function(explanation) {
                test.ok(explanation != null);
      
                db.close();
              });
            })
          });
        });
      });
      // A more complex ensureIndex using a compound unique index in the background and dropping duplicated documents 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');
        var collection = db.collection('ensureIndexExample1_with_generators');
        // Insert a bunch of documents for the index
        yield collection.insertMany([{a:1, b:1}
          , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1});
      
        // Create an index on the a field
        yield db.ensureIndex('ensureIndexExample1_with_generators', {a:1, b:1}
          , {unique:true, background:true, w:1});
      
        // Show that duplicate records got dropped
        var items = yield collection.find({}).toArray();
        test.equal(4, items.length);
      
        // Perform a query, with explain to show we hit the query
        var explanation = yield collection.find({a:2}).explain();
        test.ok(explanation != null);
      
        db.close();
      });
      // A more complex ensureIndex using a compound unique index in the background 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');
        var collection = db.collection('ensureIndexExample2_with_generators');
        // Insert a bunch of documents for the index
        yield collection.insertMany([{a:1, b:1}
          , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1});
      
        // Create an index on the a field
        yield collection.ensureIndex({a:1, b:1}
          , {unique:true, background:true, w:1});
      
        // Show that duplicate records got dropped
        var items = yield collection.find({}).toArray();
        test.equal(4, items.length);
      
        // Perform a query, with explain to show we hit the query
        var explanation = yield collection.find({a:2}).explain();
        test.ok(explanation != null);
      
        // Close db
        db.close();
      });

      Creates a cursor for a query that can be used to iterate over results from MongoDB

      Name Type Description
      query object

      The cursor query object.

      Throws:
      Examples
      // A simple query using the find method on the collection.
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
      
        // Create a collection we want to drop later
        var collection = db.collection('simple_query');
      
        // Insert a bunch of documents for the testing
        collection.insertMany([{a:1}, {a:2}, {a:3}], {w:1}, function(err, result) {
          test.equal(null, err);
      
          // Perform a simple find and return all the documents
          collection.find().toArray(function(err, docs) {
            test.equal(null, err);
            test.equal(3, docs.length);
      
            db.close();
          });
        });
      });
      // A simple query showing the explain for a query
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
      
        // Create a collection we want to drop later
        var collection = db.collection('simple_explain_query');
        // Insert a bunch of documents for the testing
        collection.insertMany([{a:1}, {a:2}, {a:3}], {w:1}, function(err, result) {
          test.equal(null, err);
      
          // Perform a simple find and return all the documents
          collection.find({}).explain(function(err, explain) {
            test.equal(null, err);
            test.ok(explain != null);
      
            db.close();
          });
        });
      });
      // A simple query showing skip and limit
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
      
        // Create a collection we want to drop later
        var collection = db.collection('simple_limit_skip_query');
        // Insert a bunch of documents for the testing
        collection.insertMany([{a:1, b:1}, {a:2, b:2}, {a:3, b:3}], {w:1}, function(err, result) {
          test.equal(null, err);
      
          // Perform a simple find and return all the documents
          collection.find({})
            .skip(1).limit(1).project({b:1}).toArray(function(err, docs) {
              test.equal(null, err);
              test.equal(1, docs.length);
              test.equal(null, docs[0].a);
              test.equal(2, docs[0].b);
      
              db.close();
          });
        });
      });
      // A simple query using the find method and toArray method with a Promise.
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
      
        // Create a collection we want to drop later
        var collection = db.collection('simple_query_with_promise');
      
        // Insert a bunch of documents for the testing
        collection.insertMany([{a:1}, {a:2}, {a:3}], {w:1}).then(function(result) {
      
          // Perform a simple find and return all the documents
          collection.find().toArray().then(function(docs) {
            test.equal(3, docs.length);
      
            db.close();
          });
        });
      });
      // A simple query showing the explain for a query using a Promise.
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
      
        // Create a collection we want to drop later
        var collection = db.collection('simple_explain_query_with_promise');
        // Insert a bunch of documents for the testing
        collection.insertMany([{a:1}, {a:2}, {a:3}], {w:1}).then(function(result) {
      
          // Perform a simple find and return all the documents
          collection.find({}).explain().then(function(docs) {
            test.ok(docs != null);
      
            db.close();
          });
        });
      });
      // A simple query showing skip and limit using a Promise.
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
      
        // Create a collection we want to drop later
        var collection = db.collection('simple_limit_skip_query_with_promise');
        // Insert a bunch of documents for the testing
        collection.insertMany([{a:1, b:1}, {a:2, b:2}, {a:3, b:3}], {w:1}).then(function(result) {
      
          // Perform a simple find and return all the documents
          collection.find({})
            .skip(1).limit(1).project({b:1}).toArray().then(function(docs) {
              test.equal(1, docs.length);
              test.equal(null, docs[0].a);
              test.equal(2, docs[0].b);
      
              db.close();
          });
        });
      });
      // A simple query using the find method and toArray method with 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');
      
        // Create a collection we want to drop later
        var collection = db.collection('simple_query_with_generators');
      
        // Insert a bunch of documents for the testing
        yield collection.insertMany([{a:1}, {a:2}, {a:3}], {w:1});
      
        // Perform a simple find and return all the documents
        var docs = yield collection.find().toArray();
        test.equal(3, docs.length);
      
        // Close the db
        db.close();
      });
      // A simple query showing the explain for a query 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');
      
        // Create a collection we want to drop later
        var collection = db.collection('simple_explain_query_with_generators');
        // Insert a bunch of documents for the testing
        yield collection.insertMany([{a:1}, {a:2}, {a:3}], {w:1});
      
        // Perform a simple find and return all the documents
        var explain = yield collection.find({}).explain();
        test.ok(explain != null);
      
        db.close();
      });
      // A simple query showing skip and limit 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');
      
        // Create a collection we want to drop later
        var collection = db.collection('simple_limit_skip_query_with_generators');
        // Insert a bunch of documents for the testing
        yield collection.insertMany([{a:1, b:1}, {a:2, b:2}, {a:3, b:3}], {w:1});
      
        // Perform a simple find and return all the documents
        var docs = yield collection.find({})
        .skip(1).limit(1).project({b:1}).toArray();
          test.equal(1, docs.length);
          test.equal(null, docs[0].a);
          test.equal(2, docs[0].b);
      
          // Close db
          db.close();
      });

      findAndModify(query, sort, doc, options, callback){Promise}

      Find and update a document.

      Name Type Default Description
      query object

      Query object to locate the object to modify.

      sort array

      If multiple docs match, choose the first one in the specified sort order as the object to manipulate.

      doc object

      The fields/vals to be updated.

      options object null optional

      Optional settings.

      Name Type Default Description
      w number | string null optional

      The write concern.

      wtimeout number null optional

      The write concern timeout.

      j boolean false optional

      Specify a journal write concern.

      remove boolean false optional

      Set to true to remove the object before returning.

      upsert boolean false optional

      Perform an upsert operation.

      new boolean false optional

      Set to true if you want to return the modified object rather than the original. Ignored for remove.

      fields object null optional

      Object containing the field projection for the result returned from the operation.

      callback Collection~findAndModifyCallback optional

      The command result callback

      Deprecated
      • use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead
        Returns:
        Promise if no callback passed
        Examples
        // A whole set of different ways to use the findAndModify command.
        // The first findAndModify command modifies a document and returns the modified document back.
        The second findAndModify command removes the document.
        The second findAndModify command upserts a document and returns the new document. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a collection we want to drop later var collection = db.collection('simple_find_and_modify_operations_'); // Insert some test documentations collection.insertMany([{a:1}, {b:1}, {c:1}], {w:1}, function(err, result) { test.equal(null, err); // Simple findAndModify command returning the new document collection.findAndModify({a:1}, [['a', 1]], {$set:{b1:1}}, {new:true}, function(err, doc) { test.equal(null, err); test.equal(1, doc.value.a); test.equal(1, doc.value.b1); // Simple findAndModify command returning the new document and // removing it at the same time collection.findAndModify({b:1}, [['b', 1]], {$set:{b:2}}, {remove:true}, function(err, doc) { // Verify that the document is gone collection.findOne({b:1}, function(err, item) { test.equal(null, err); test.equal(null, item); // Simple findAndModify command performing an upsert and returning the new document // executing the command safely collection.findAndModify({d:1}, [['b', 1]], {d:1, f:1}, {new:true, upsert:true, w:1}, function(err, doc) { test.equal(null, err); test.equal(1, doc.value.d); test.equal(1, doc.value.f); db.close(); }) }); }); }); }); });
        // A whole set of different ways to use the findAndModify command with a Promise..
        // The first findAndModify command modifies a document and returns the modified document back.
        The second findAndModify command removes the document.
        The second findAndModify command upserts a document and returns the new document. var MongoClient = require('mongodb').MongoClient, test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Create a collection we want to drop later var collection = db.collection('simple_find_and_modify_operations_with_promise'); // Insert some test documentations collection.insertMany([{a:1}, {b:1}, {c:1}], {w:1}).then(function(result) { // Simple findAndModify command returning the new document collection.findAndModify({a:1}, [['a', 1]], {$set:{b1:1}}, {new:true}).then(function(doc) { test.equal(1, doc.value.a); test.equal(1, doc.value.b1); // Simple findAndModify command returning the new document and // removing it at the same time collection.findAndModify({b:1}, [['b', 1]], {$set:{b:2}}, {remove:true}).then(function(doc) { // Verify that the document is gone collection.findOne({b:1}).then(function(item) { test.equal(null, item); // Simple findAndModify command performing an upsert and returning the new document // executing the command safely collection.findAndModify({d:1}, [['b', 1]], {d:1, f:1}, {new:true, upsert:true, w:1}).then(function(doc) { test.equal(1, doc.value.d); test.equal(1, doc.value.f); db.close(); }) }); }); }); }); });
        // A whole set of different ways to use the findAndModify command with a Generator and the co module..
        // The first findAndModify command modifies a document and returns the modified document back.
        The second findAndModify command removes the document.
        The second findAndModify command upserts a document and returns the new document. var MongoClient = require('mongodb').MongoClient, co = require('co'); test = require('assert'); co(function*() { var db = yield MongoClient.connect('mongodb://localhost:27017/test'); // Create a collection we want to drop later var collection = db.collection('simple_find_and_modify_operations_with_generators'); // Insert some test documentations yield collection.insertMany([{a:1}, {b:1}, {c:1}], {w:1}); // Simple findAndModify command returning the new document var doc = yield collection.findAndModify({a:1}, [['a', 1]], {$set:{b1:1}}, {new:true}); test.equal(1, doc.value.a); test.equal(1, doc.value.b1); // Simple findAndModify command returning the new document and // removing it at the same time var doc = yield collection.findAndModify({b:1}, [['b', 1]], {$set:{b:2}}, {remove:true}); // Verify that the document is gone var item = yield collection.findOne({b:1}); test.equal(null, item); // Simple findAndModify command performing an upsert and returning the new document // executing the command safely var doc = yield collection.findAndModify({d:1}, [['b', 1]], {d:1, f:1}, {new:true, upsert:true, w:1}); test.equal(1, doc.value.d); test.equal(1, doc.value.f); // Close the db db.close(); });

        findAndRemove(query, sort, options, callback){Promise}

        Find and remove a document.

        Name Type Default Description
        query object

        Query object to locate the object to modify.

        sort array

        If multiple docs match, choose the first one in the specified sort order as the object to manipulate.

        options object null optional

        Optional settings.

        Name Type Default Description
        w number | string null optional

        The write concern.

        wtimeout number null optional

        The write concern timeout.

        j boolean false optional

        Specify a journal write concern.

        callback Collection~resultCallback optional

        The command result callback

        Deprecated
        • use findOneAndDelete instead
          Returns:
          Promise if no callback passed
          Examples
          // An example of using findAndRemove
          
          var MongoClient = require('mongodb').MongoClient,
            test = require('assert');
          MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
          
            // Create a collection we want to drop later
            var collection = db.collection('simple_find_and_modify_operations_2');
            // Insert some test documentations
            collection.insertMany([{a:1}, {b:1, d:1}, {c:1}], {w:1}, function(err, result) {
              test.equal(null, err);
          
              // Simple findAndModify command returning the old document and
              // removing it at the same time
              collection.findAndRemove({b:1}, [['b', 1]], function(err, doc) {
                test.equal(null, err);
                test.equal(1, doc.value.b);
                test.equal(1, doc.value.d);
          
                // Verify that the document is gone
                collection.findOne({b:1}, function(err, item) {
                  test.equal(null, err);
                  test.equal(null, item);
          
                  db.close();
                });
              });
            });
          });
          // An example of using findAndRemove using a Promise.
          
          var MongoClient = require('mongodb').MongoClient,
            test = require('assert');
          MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
          
            // Create a collection we want to drop later
            var collection = db.collection('simple_find_and_modify_operations_2_with_promise');
            // Insert some test documentations
            collection.insertMany([{a:1}, {b:1, d:1}, {c:1}], {w:1}).then(function(result) {
          
              // Simple findAndModify command returning the old document and
              // removing it at the same time
              collection.findAndRemove({b:1}, [['b', 1]]).then(function(doc) {
                test.equal(1, doc.value.b);
                test.equal(1, doc.value.d);
          
                // Verify that the document is gone
                collection.findOne({b:1}).then(function(item) {
                  test.equal(null, item);
          
                  db.close();
                });
              });
            });
          });
          // An example of using findAndRemove 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');
          
            // Create a collection we want to drop later
            var collection = db.collection('simple_find_and_modify_operations_2_with_generators');
            // Insert some test documentations
            yield collection.insertMany([{a:1}, {b:1, d:1}, {c:1}], {w:1});
          
            // Simple findAndModify command returning the old document and
            // removing it at the same time
            var doc = yield collection.findAndRemove({b:1}, [['b', 1]]);
            test.equal(1, doc.value.b);
            test.equal(1, doc.value.d);
          
            // Verify that the document is gone
            var item = yield collection.findOne({b:1});
            test.equal(null, item);
          
            // Db close
            db.close();
          });

          findOne(query, options, callback){Promise}

          Fetches the first document that matches the query

          Name Type Default Description
          query object

          Query for find Operation

          options object null optional

          Optional settings.

          Name Type Default Description
          limit number 0 optional

          Sets the limit of documents returned in the query.

          sort array | object null optional

          Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc.

          fields object null optional

          The fields to return in the query. Object of fields to include or exclude (not both), {'a':1}

          skip number 0 optional

          Set to skip N documents ahead in your query (useful for pagination).

          hint Object null optional

          Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1}

          explain boolean false optional

          Explain the query instead of returning the data.

          snapshot boolean false optional

          Snapshot query.

          timeout boolean false optional

          Specify if the cursor can timeout.

          tailable boolean false optional

          Specify if the cursor is tailable.

          batchSize number 0 optional

          Set the batchSize for the getMoreCommand when iterating over the query results.

          returnKey boolean false optional

          Only return the index key.

          maxScan number null optional

          Limit the number of items to scan.

          min number null optional

          Set index bounds.

          max number null optional

          Set index bounds.

          showDiskLoc boolean false optional

          Show disk location of results.

          comment string null optional

          You can put a $comment field on a query to make looking in the profiler logs simpler.

          raw boolean false optional

          Return document results as raw BSON buffers.

          promoteLongs boolean true optional

          Promotes Long values to number if they fit inside the 53 bits resolution.

          promoteValues boolean true optional

          Promotes BSON values to native types where possible, set to false to only receive wrapper types.

          promoteBuffers boolean false optional

          Promotes Binary BSON values to native Node Buffers.

          readPreference ReadPreference | string null optional

          The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).

          partial boolean false optional

          Specify if the cursor should return partial results when querying against a sharded system

          maxTimeMS number null optional

          Number of milliseconds to wait before aborting the query.

          collation object null optional

          Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).

          callback Collection~resultCallback optional

          The command result callback

          Returns:
          Promise if no callback passed
          Examples
          // A simple query using findOne
          
          var MongoClient = require('mongodb').MongoClient,
            test = require('assert');
          MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
          
            // Create a collection we want to drop later
            var collection = db.collection('simple_limit_skip_find_one_query');
            // Insert a bunch of documents for the testing
            collection.insertMany([{a:1, b:1}, {a:2, b:2}, {a:3, b:3}], {w:1}, function(err, result) {
              test.equal(null, err);
          
              // Perform a simple find and return all the documents
              collection.findOne({a:2}, {fields:{b:1}}, function(err, doc) {
                test.equal(null, err);
                test.equal(null, doc.a);
                test.equal(2, doc.b);
          
                db.close();
              });
            });
          });
          // A simple query using findOne with a Promise.
          
          var MongoClient = require('mongodb').MongoClient,
            test = require('assert');
          MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
          
            // Create a collection we want to drop later
            var collection = db.collection('simple_limit_skip_find_one_query_with_promise');
            // Insert a bunch of documents for the testing
            collection.insertMany([{a:1, b:1}, {a:2, b:2}, {a:3, b:3}], {w:1}).then(function(result) {
          
              // Perform a simple find and return all the documents
              collection.findOne({a:2}, {fields:{b:1}}).then(function(doc) {
                test.equal(null, doc.a);
                test.equal(2, doc.b);
          
                db.close();
              });
            });
          });
          // A simple query using findOne with 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');
          
            // Create a collection we want to drop later
            var collection = db.collection('simple_limit_skip_find_one_query_with_generators');
          
            // Insert a bunch of documents for the testing
            yield collection.insertMany([{a:1, b:1}, {a:2, b:2}, {a:3, b:3}], {w:1});
          
            // Perform a simple find and return all the documents
            var doc = yield collection.findOne({a:2}, {fields:{b:1}});
            test.equal(null, doc.a);
            test.equal(2, doc.b);
          
            // Db close
            db.close();
          });

          findOneAndDelete(filter, options, callback){Promise}

          Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation.

          Name Type Default Description
          filter object

          Document selection filter.

          options object null optional

          Optional settings.

          Name Type Default Description
          projection object null optional

          Limits the fields to return for all matching documents.

          sort object null optional

          Determines which document the operation modifies if the query selects multiple documents.

          maxTimeMS number null optional

          The maximum amount of time to allow the query to run.

          callback Collection~findAndModifyCallback optional

          The collection result callback

          Returns:
          Promise if no callback passed
          Examples
          // Example of a simple findOneAndDelete operation
          
          var MongoClient = require('mongodb').MongoClient,
            test = require('assert');
          MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
            // Get the collection
            var col = db.collection('find_one_and_delete');
            col.insertMany([{a:1, b:1}], {w:1}, function(err, r) {
              test.equal(null, err);
              test.equal(1, r.result.n);
          
              col.findOneAndDelete({a:1}
                , { projection: {b:1}, sort: {a:1} }
                , function(err, r) {
                  test.equal(null, err);
                  test.equal(1, r.lastErrorObject.n);
                  test.equal(1, r.value.b);
          
                  db.close();
              });
            });
          });
          // Example of a simple findOneAndDelete operation using a Promise.
          
          var MongoClient = require('mongodb').MongoClient,
            test = require('assert');
          MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
            // Get the collection
            var col = db.collection('find_one_and_delete_with_promise');
            col.insertMany([{a:1, b:1}], {w:1}).then(function(r) {
              test.equal(1, r.result.n);
          
              col.findOneAndDelete({a:1}
                , { projection: {b:1}, sort: {a:1} }
                ).then(function(r) {
                  test.equal(1, r.lastErrorObject.n);
                  test.equal(1, r.value.b);
          
                  db.close();
              });
            });
          });
          // Example of a simple findOneAndDelete operation 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');
            // Get the collection
            var col = db.collection('find_one_and_delete_with_generators');
            var r = yield col.insertMany([{a:1, b:1}], {w:1});
            test.equal(1, r.result.n);
          
            var r = yield col.findOneAndDelete({a:1}
              , { projection: {b:1}, sort: {a:1} }
              );
            test.equal(1, r.lastErrorObject.n);
            test.equal(1, r.value.b);
          
            db.close();
          });

          findOneAndReplace(filter, replacement, options, callback){Promise}

          Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation.

          Name Type Default Description
          filter object

          Document selection filter.

          replacement object

          Document replacing the matching document.

          options object null optional

          Optional settings.

          Name Type Default Description
          projection object null optional

          Limits the fields to return for all matching documents.

          sort object null optional

          Determines which document the operation modifies if the query selects multiple documents.

          maxTimeMS number null optional

          The maximum amount of time to allow the query to run.

          upsert boolean false optional

          Upsert the document if it does not exist.

          returnOriginal boolean true optional

          When false, returns the updated document rather than the original. The default is true.

          callback Collection~findAndModifyCallback optional

          The collection result callback

          Returns:
          Promise if no callback passed
          Examples
          // Example of a simple findOneAndReplace operation
          
          var MongoClient = require('mongodb').MongoClient,
            test = require('assert');
          MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
            // Get the collection
            var col = db.collection('find_one_and_replace');
            col.insertMany([{a:1, b:1}], {w:1}, function(err, r) {
              test.equal(null, err);
              test.equal(1, r.result.n);
          
              col.findOneAndReplace({a:1}
                , {c:1, b:1}
                , {
                      projection: {b:1, c:1}
                    , sort: {a:1}
                    , returnOriginal: false
                    , upsert: true
                  }
                , function(err, r) {
                  test.equal(null, err);
                  test.equal(1, r.lastErrorObject.n);
                  test.equal(1, r.value.b);
                  test.equal(1, r.value.c);
          
                  db.close();
              });
            });
          });
          // Example of a simple findOneAndReplace operation using a Promise.
          
          var MongoClient = require('mongodb').MongoClient,
            test = require('assert');
          MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
            // Get the collection
            var col = db.collection('find_one_and_replace_with_promise');
            col.insertMany([{a:1, b:1}], {w:1}).then(function(r) {
              test.equal(1, r.result.n);
          
              col.findOneAndReplace({a:1}
                , {c:1, b:1}
                , {
                      projection: {b:1, c:1}
                    , sort: {a:1}
                    , returnOriginal: false
                    , upsert: true
                  }
                ).then(function(r) {
                  test.equal(1, r.lastErrorObject.n);
                  test.equal(1, r.value.b);
                  test.equal(1, r.value.c);
          
                  db.close();
              });
            });
          });
          // Example of a simple findOneAndReplace operation 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');
            // Get the collection
            var col = db.collection('find_one_and_replace_with_generators');
            var r = yield col.insertMany([{a:1, b:1}], {w:1});
            test.equal(1, r.result.n);
          
            var r = yield col.findOneAndReplace({a:1}
              , {c:1, b:1}
              , {
                    projection: {b:1, c:1}
                  , sort: {a:1}
                  , returnOriginal: false
                  , upsert: true
                }
              );
            test.equal(1, r.lastErrorObject.n);
            test.equal(1, r.value.b);
            test.equal(1, r.value.c);
          
            db.close();
          });

          findOneAndUpdate(filter, update, options, callback){Promise}

          Find a document and update it in one atomic operation, requires a write lock for the duration of the operation.

          Name Type Default Description
          filter object

          Document selection filter.

          update object

          Update operations to be performed on the document

          options object null optional

          Optional settings.

          Name Type Default Description
          projection object null optional

          Limits the fields to return for all matching documents.

          sort object null optional

          Determines which document the operation modifies if the query selects multiple documents.

          maxTimeMS number null optional

          The maximum amount of time to allow the query to run.

          upsert boolean false optional

          Upsert the document if it does not exist.

          returnOriginal boolean true optional

          When false, returns the updated document rather than the original. The default is true.

          callback Collection~findAndModifyCallback optional

          The collection result callback

          Returns:
          Promise if no callback passed
          Examples
          // Example of a simple findOneAndUpdate operation
          
          var MongoClient = require('mongodb').MongoClient,
            test = require('assert');
          MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
            // Get the collection
            var col = db.collection('find_one_and_update');
            col.insertMany([{a:1, b:1}], {w:1}, function(err, r) {
              test.equal(null, err);
              test.equal(1, r.result.n);
          
              col.findOneAndUpdate({a:1}
                , {$set: {d:1}}
                , {
                      projection: {b:1, d:1}
                    , sort: {a:1}
                    , returnOriginal: false
                    , upsert: true
                  }
                , function(err, r) {
                  test.equal(null, err);
                  test.equal(1, r.lastErrorObject.n);
                  test.equal(1, r.value.b);
                  test.equal(1, r.value.d);
          
                  db.close();
              });
            });
          });
          // Example of a simple findOneAndUpdate operation using a Promise.
          
          var MongoClient = require('mongodb').MongoClient,
            test = require('assert');
          MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
            // Get the collection
            var col = db.collection('find_one_and_update_with_promise');
            col.insertMany([{a:1, b:1}], {w:1}).then(function(r) {
              test.equal(1, r.result.n);
          
              col.findOneAndUpdate({a:1}
                , {$set: {d:1}}
                , {
                      projection: {b:1, d:1}
                    , sort: {a:1}
                    , returnOriginal: false
                    , upsert: true
                  }
                ).then(function(r) {
                  test.equal(1, r.lastErrorObject.n);
                  test.equal(1, r.value.b);
                  test.equal(1, r.value.d);
          
                  db.close();
              });
            });
          });
          // Example of a simple findOneAndUpdate operation 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');
            // Get the collection
            var col = db.collection('find_one_and_update_with_generators');
            var r = yield col.insertMany([{a:1, b:1}], {w:1});
            test.equal(1, r.result.n);
          
            var r = yield col.findOneAndUpdate({a:1}
              , {$set: {d:1}}
              , {
                    projection: {b:1, d:1}
                  , sort: {a:1}
                  , returnOriginal: false
                  , upsert: true
                }
              );
            test.equal(1, r.lastErrorObject.n);
            test.equal(1, r.value.b);
            test.equal(1, r.value.d);
          
            db.close();
          });

          geoHaystackSearch(x, y, options, callback){Promise}

          Execute a geo search using a geo haystack index on a collection.

          Name Type Default Description
          x number

          Point to search on the x axis, ensure the indexes are ordered in the same order.

          y number

          Point to search on the y axis, ensure the indexes are ordered in the same order.

          options object null optional

          Optional settings.

          Name Type Default Description
          readPreference ReadPreference | string null optional

          The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).

          maxDistance number null optional

          Include results up to maxDistance from the point.

          search object null optional

          Filter the results by a query.

          limit number false optional

          Max number of results to return.

          callback Collection~resultCallback optional

          The command result callback

          Returns:
          Promise if no callback passed
          Examples
          // Example of a simple geoHaystackSearch query across some documents
          
          var MongoClient = require('mongodb').MongoClient,
            test = require('assert');
          MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
          
            // Fetch the collection
            var collection = db.collection("simple_geo_haystack_command");
          
            // Add a location based index
            collection.ensureIndex({loc: "geoHaystack", type: 1}, {bucketSize: 1}, function(err, result) {
          
              // Save a new location tagged document
              collection.insertMany([{a:1, loc:[50, 30]}, {a:1, loc:[30, 50]}], {w:1}, function(err, result) {
          
                // Use geoNear command to find document
                collection.geoHaystackSearch(50, 50, {search:{a:1}, limit:1, maxDistance:100}, function(err, docs) {
                  test.equal(1, docs.results.length);
                  db.close();
                });
              });
            });
          });
          // Example of a simple geoHaystackSearch query across some documents using a Promise.
          
          var MongoClient = require('mongodb').MongoClient,
            test = require('assert');
          MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
          
            // Fetch the collection
            var collection = db.collection("simple_geo_haystack_command_with_promise");
          
            // Add a location based index
            collection.ensureIndex({loc: "geoHaystack", type: 1}, {bucketSize: 1}).then(function(result) {
          
              // Save a new location tagged document
              collection.insertMany([{a:1, loc:[50, 30]}, {a:1, loc:[30, 50]}], {w:1}).then(function(result) {
          
                // Use geoNear command to find document
                collection.geoHaystackSearch(50, 50, {search:{a:1}, limit:1, maxDistance:100}).then(function(docs) {
                  test.equal(1, docs.results.length);
                  db.close();
                });
              });
            });
          });
          // Example of a simple geoHaystackSearch query across some documents 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');
          
            // Fetch the collection
            var collection = db.collection("simple_geo_haystack_command_with_generators");
          
            // Add a location based index
            yield collection.ensureIndex({loc: "geoHaystack", type: 1}, {bucketSize: 1});
          
            // Save a new location tagged document
            yield collection.insertMany([{a:1, loc:[50, 30]}, {a:1, loc:[30, 50]}], {w:1});
          
            // Use geoNear command to find document
            var docs = yield collection.geoHaystackSearch(50, 50, {search:{a:1}, limit:1, maxDistance:100});
            test.equal(1, docs.results.length);
            db.close();
          });

          geoNear(x, y, options, callback){Promise}

          Execute the geoNear command to search for items in the collection

          Name Type Default Description
          x number

          Point to search on the x axis, ensure the indexes are ordered in the same order.

          y number

          Point to search on the y axis, ensure the indexes are ordered in the same order.

          options object null optional

          Optional settings.

          Name Type Default Description
          readPreference ReadPreference | string null optional

          The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).

          num number null optional

          Max number of results to return.

          minDistance number null optional

          Include results starting at minDistance from a point (2.6 or higher)

          maxDistance number null optional

          Include results up to maxDistance from the point.

          distanceMultiplier number null optional

          Include a value to multiply the distances with allowing for range conversions.

          query object null optional

          Filter the results by a query.

          spherical boolean false optional

          Perform query using a spherical model.

          uniqueDocs boolean false optional

          The closest location in a document to the center of the search region will always be returned MongoDB > 2.X.

          includeLocs boolean false optional

          Include the location data fields in the top level of the results MongoDB > 2.X.

          callback Collection~resultCallback optional

          The command result callback

          Returns:
          Promise if no callback passed
          Examples
          // Example of a simple geoNear query across some documents
          
          var MongoClient = require('mongodb').MongoClient,
            test = require('assert');
          MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
          
            // Fetch the collection
            var collection = db.collection("simple_geo_near_command");
          
            // Add a location based index
            collection.ensureIndex({loc:"2d"}, function(err, result) {
          
              // Save a new location tagged document
              collection.insertMany([{a:1, loc:[50, 30]}, {a:1, loc:[30, 50]}], {w:1}, function(err, result) {
          
                // Use geoNear command to find document
                collection.geoNear(50, 50, {query:{a:1}, num:1}, function(err, docs) {
                  test.equal(1, docs.results.length);
          
                  db.close();
                });
              });
            });
          });
          // Example of a simple geoNear query across some documents using a Promise.
          
          var MongoClient = require('mongodb').MongoClient,
            test = require('assert');
          MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
          
            // Fetch the collection
            var collection = db.collection("simple_geo_near_command_with_promise");
          
            // Add a location based index
            collection.ensureIndex({loc:"2d"}).then(function(result) {
          
              // Save a new location tagged document
              collection.insertMany([{a:1, loc:[50, 30]}, {a:1, loc:[30, 50]}], {w:1}).then(function(result) {
          
                // Use geoNear command to find document
                collection.geoNear(50, 50, {query:{a:1}, num:1}).then(function(docs) {
                  test.equal(1, docs.results.length);
          
                  db.close();
                });
              });
            });
          });
          // Example of a simple geoNear query across some documents 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');
          
            // Fetch the collection
            var collection = db.collection("simple_geo_near_command_with_generators");
          
            // Add a location based index
            yield collection.ensureIndex({loc:"2d"});
          
            // Save a new location tagged document
            yield collection.insertMany([{a:1, loc:[50, 30]}, {a:1, loc:[30, 50]}], {w:1});
          
            // Use geoNear command to find document
            var docs = yield collection.geoNear(50, 50, {query:{a:1}, num:1});
            test.equal(1, docs.results.length);
          
            // Close db
            db.close();
          });

          group(keys, condition, initial, reduce, finalize, command, options, callback){Promise}

          Run a group command across a collection

          Name Type Default Description
          keys object | array | function | code

          An object, array or function expressing the keys to group by.

          condition object

          An optional condition that must be true for a row to be considered.

          initial object

          Initial value of the aggregation counter object.

          reduce function | Code

          The reduce function aggregates (reduces) the objects iterated

          finalize function | Code

          An optional function to be run on each item in the result set just before the item is returned.

          command boolean

          Specify if you wish to run using the internal group command or using eval, default is true.

          options object null optional

          Optional settings.

          Name Type Default Description
          readPreference ReadPreference | string null optional

          The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).

          callback Collection~resultCallback optional

          The command result callback

          Deprecated
          • MongoDB 3.6 or higher will no longer support the group command. We recommend rewriting using the aggregation framework.
            Returns:
            Promise if no callback passed
            Examples
            // A whole lot of different ways to execute the group command
            
            var MongoClient = require('mongodb').MongoClient,
              Code = require('mongodb').Code,
              test = require('assert');
            MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
            
              // Create a test collection
              var collection = db.collection('test_group');
            
              // Perform a simple group by on an empty collection
              collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }", function(err, results) {
                test.deepEqual([], results);
            
                // Trigger some inserts on the collection
                collection.insertMany([{'a':2}, {'b':5}, {'a':1}], {w:1}, function(err, ids) {
            
                  // Perform a group count
                  collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }", function(err, results) {
                    test.equal(3, results[0].count);
            
                    // Perform a group count using the eval method
                    collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }", false, function(err, results) {
                      test.equal(3, results[0].count);
            
                      // Group with a conditional
                      collection.group([], {'a':{'$gt':1}}, {"count":0}, "function (obj, prev) { prev.count++; }", function(err, results) {
                        // Results
                        test.equal(1, results[0].count);
            
                        // Group with a conditional using the EVAL method
                        collection.group([], {'a':{'$gt':1}}, {"count":0}, "function (obj, prev) { prev.count++; }" , false, function(err, results) {
                          // Results
                          test.equal(1, results[0].count);
            
                          // Insert some more test data
                          collection.insertMany([{'a':2}, {'b':3}], {w:1}, function(err, ids) {
            
                            // Do a Group by field a
                            collection.group(['a'], {}, {"count":0}, "function (obj, prev) { prev.count++; }", function(err, results) {
                              // Results
                              test.equal(2, results[0].a);
                              test.equal(2, results[0].count);
                              test.equal(null, results[1].a);
                              test.equal(2, results[1].count);
                              test.equal(1, results[2].a);
                              test.equal(1, results[2].count);
            
                              // Do a Group by field a
                              collection.group({'a':true}, {}, {"count":0}, function (obj, prev) { prev.count++; }, true, function(err, results) {
                                // Results
                                test.equal(2, results[0].a);
                                test.equal(2, results[0].count);
                                test.equal(null, results[1].a);
                                test.equal(2, results[1].count);
                                test.equal(1, results[2].a);
                                test.equal(1, results[2].count);
            
                                // Correctly handle illegal function
                                collection.group([], {}, {}, "5 ++ 5", function(err, results) {
                                  test.ok(err.message != null);
            
                                  // Use a function to select the keys used to group by
                                  var keyf = function(doc) { return {a: doc.a}; };
                                  collection.group(keyf, {a: {$gt: 0}}, {"count": 0, "value": 0}, function(obj, prev) { prev.count++; prev.value += obj.a; }, true, function(err, results) {
                                    // Results
                                    results.sort(function(a, b) { return b.count - a.count; });
                                    test.equal(2, results[0].count);
                                    test.equal(2, results[0].a);
                                    test.equal(4, results[0].value);
                                    test.equal(1, results[1].count);
                                    test.equal(1, results[1].a);
                                    test.equal(1, results[1].value);
            
                                    // Use a Code object to select the keys used to group by
                                    var keyf = new Code(function(doc) { return {a: doc.a}; });
                                    collection.group(keyf, {a: {$gt: 0}}, {"count": 0, "value": 0}, function(obj, prev) { prev.count++; prev.value += obj.a; }, true, function(err, results) {
                                      // Results
                                      results.sort(function(a, b) { return b.count - a.count; });
                                      test.equal(2, results[0].count);
                                      test.equal(2, results[0].a);
                                      test.equal(4, results[0].value);
                                      test.equal(1, results[1].count);
                                      test.equal(1, results[1].a);
                                      test.equal(1, results[1].value);
            
                                      // Correctly handle illegal function when using the EVAL method
                                      collection.group([], {}, {}, "5 ++ 5", false, function(err, results) {
                                        test.ok(err.message != null);
            
                                        db.close();
                                      });
                                    });
                                  });
                                });
                              });
                            });
                          });
                        });
                      });
                    });
                  });
                });
              });
            });
            // A whole lot of different ways to execute the group command using a Promise.
            
            var MongoClient = require('mongodb').MongoClient,
              Code = require('mongodb').Code,
              test = require('assert');
            MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
            
              // Create a test collection
              var collection = db.collection('test_group_with_promise');
            
              // Perform a simple group by on an empty collection
              collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }").then(function(results) {
                test.deepEqual([], results);
            
                // Trigger some inserts on the collection
                collection.insertMany([{'a':2}, {'b':5}, {'a':1}], {w:1}).then(function(ids) {
            
                  // Perform a group count
                  collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }").then(function(results) {
                    test.equal(3, results[0].count);
            
                    // Perform a group count using the eval method
                    collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }", false).then(function(results) {
                      test.equal(3, results[0].count);
            
                      // Group with a conditional
                      collection.group([], {'a':{'$gt':1}}, {"count":0}, "function (obj, prev) { prev.count++; }").then(function(results) {
                        // Results
                        test.equal(1, results[0].count);
            
                        // Group with a conditional using the EVAL method
                        collection.group([], {'a':{'$gt':1}}, {"count":0}, "function (obj, prev) { prev.count++; }" , false).then(function(results) {
                          // Results
                          test.equal(1, results[0].count);
                          // Insert some more test data
                          collection.insertMany([{'a':2}, {'b':3}], {w:1}).then(function(ids) {
            
                            // Do a Group by field a
                            collection.group(['a'], {}, {"count":0}, "function (obj, prev) { prev.count++; }").then(function(results) {
                              // Results
                              test.equal(2, results[0].a);
                              test.equal(2, results[0].count);
                              test.equal(null, results[1].a);
                              test.equal(2, results[1].count);
                              test.equal(1, results[2].a);
                              test.equal(1, results[2].count);
            
                              // Do a Group by field a
                              collection.group({'a':true}, {}, {"count":0}, function (obj, prev) { prev.count++; }, true).then(function(results) {
                                // Results
                                test.equal(2, results[0].a);
                                test.equal(2, results[0].count);
                                test.equal(null, results[1].a);
                                test.equal(2, results[1].count);
                                test.equal(1, results[2].a);
                                test.equal(1, results[2].count);
            
                                // Correctly handle illegal function
                                collection.group([], {}, {}, "5 ++ 5").then(function(err, results) {
                                }).catch(function(err) {
                                  test.ok(err.message != null);
            
                                  // Use a function to select the keys used to group by
                                  var keyf = function(doc) { return {a: doc.a}; };
                                  collection.group(keyf, {a: {$gt: 0}}, {"count": 0, "value": 0}, function(obj, prev) { prev.count++; prev.value += obj.a; }, true).then(function(results) {
                                    // Results
                                    results.sort(function(a, b) { return b.count - a.count; });
                                    test.equal(2, results[0].count);
                                    test.equal(2, results[0].a);
                                    test.equal(4, results[0].value);
                                    test.equal(1, results[1].count);
                                    test.equal(1, results[1].a);
                                    test.equal(1, results[1].value);
            
                                    // Use a Code object to select the keys used to group by
                                    var keyf = new Code(function(doc) { return {a: doc.a}; });
                                    collection.group(keyf, {a: {$gt: 0}}, {"count": 0, "value": 0}, function(obj, prev) { prev.count++; prev.value += obj.a; }, true).then(function(results) {
                                      // Results
                                      results.sort(function(a, b) { return b.count - a.count; });
                                      test.equal(2, results[0].count);
                                      test.equal(2, results[0].a);
                                      test.equal(4, results[0].value);
                                      test.equal(1, results[1].count);
                                      test.equal(1, results[1].a);
                                      test.equal(1, results[1].value);
            
                                      // Correctly handle illegal function when using the EVAL method
                                      collection.group([], {}, {}, "5 ++ 5", false).then(function(results) {
                                      }).catch(function(err) {
                                        test.ok(err.message != null);
            
                                        db.close();
                                      });
                                    });
                                  });
                                });
                              });
                            });
                          });
                        });
                      });
                    });
                  });
                });
              });
            });
            // A whole lot of different ways to execute the group command using a Generator and the co module.
            
            var MongoClient = require('mongodb').MongoClient,
              Code = require('mongodb').Code;
              co = require('co');
              test = require('assert');
            
            co(function*() {
              var db = yield MongoClient.connect('mongodb://localhost:27017/test');
            
              // Create a test collection
              var collection = db.collection('test_group_with_generators');
            
              // Perform a simple group by on an empty collection
              var results = yield collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }");
              test.deepEqual([], results);
            
              // Trigger some inserts on the collection
              yield collection.insertMany([{'a':2}, {'b':5}, {'a':1}], {w:1});
            
              // Perform a group count
              var results = yield collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }");
              test.equal(3, results[0].count);
            
              // Perform a group count using the eval method
              var results = yield collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }", false);
              test.equal(3, results[0].count);
            
              // Group with a conditional
              var results = yield collection.group([], {'a':{'$gt':1}}, {"count":0}, "function (obj, prev) { prev.count++; }");
              // Results
              test.equal(1, results[0].count);
            
              // Group with a conditional using the EVAL method
              var results = yield collection.group([], {'a':{'$gt':1}}, {"count":0}, "function (obj, prev) { prev.count++; }" , false);
              // Results
              test.equal(1, results[0].count);
            
              // Insert some more test data
              yield collection.insertMany([{'a':2}, {'b':3}], {w:1});
            
              // Do a Group by field a
              var results = yield collection.group(['a'], {}, {"count":0}, "function (obj, prev) { prev.count++; }");
              // Results
              test.equal(2, results[0].a);
              test.equal(2, results[0].count);
              test.equal(null, results[1].a);
              test.equal(2, results[1].count);
              test.equal(1, results[2].a);
              test.equal(1, results[2].count);
            
              // Do a Group by field a
              var results = yield collection.group({'a':true}, {}, {"count":0}, function (obj, prev) { prev.count++; }, true);
              // Results
              test.equal(2, results[0].a);
              test.equal(2, results[0].count);
              test.equal(null, results[1].a);
              test.equal(2, results[1].count);
              test.equal(1, results[2].a);
              test.equal(1, results[2].count);
            
              try {
                // Correctly handle illegal function
                var results = yield collection.group([], {}, {}, "5 ++ 5")
              } catch(err) {
                test.ok(err.message != null);
            
                // Use a function to select the keys used to group by
                var keyf = function(doc) { return {a: doc.a}; };
                var results = yield collection.group(keyf, {a: {$gt: 0}}, {"count": 0, "value": 0}, function(obj, prev) { prev.count++; prev.value += obj.a; }, true);
                // Results
                results.sort(function(a, b) { return b.count - a.count; });
                test.equal(2, results[0].count);
                test.equal(2, results[0].a);
                test.equal(4, results[0].value);
                test.equal(1, results[1].count);
                test.equal(1, results[1].a);
                test.equal(1, results[1].value);
            
                // Use a Code object to select the keys used to group by
                var keyf = new Code(function(doc) { return {a: doc.a}; });
                var results = yield collection.group(keyf, {a: {$gt: 0}}, {"count": 0, "value": 0}, function(obj, prev) { prev.count++; prev.value += obj.a; }, true);
                // Results
                results.sort(function(a, b) { return b.count - a.count; });
                test.equal(2, results[0].count);
                test.equal(2, results[0].a);
                test.equal(4, results[0].value);
                test.equal(1, results[1].count);
                test.equal(1, results[1].a);
                test.equal(1, results[1].value);
            
                try {
                  yield collection.group([], {}, {}, "5 ++ 5", false);
                } catch(err) {
                  test.ok(err.message != null);
            
                  db.close();
                }
              };
            });

            indexes(callback){Promise}

            Retrieve all the indexes on the collection.

            Name Type Description
            callback Collection~resultCallback optional

            The command result callback

            Returns:
            Promise if no callback passed
            Examples
            // Example of retrieving a collections indexes
            
            var MongoClient = require('mongodb').MongoClient,
              test = require('assert');
            MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
              // Crete the collection for the distinct example
              var collection = db.collection('simple_key_based_distinct');
              // Create a geo 2d index
              collection.ensureIndex({loc:"2d"}, {w:1}, function(err, result) {
                test.equal(null, err);
            
                // Create a simple single field index
                collection.ensureIndex({a:1}, {w:1}, function(err, result) {
                  test.equal(null, err);
            
                  setTimeout(function() {
                    // List all of the indexes on the collection
                    collection.indexes(function(err, indexes) {
                      test.equal(3, indexes.length);
            
                      db.close();
                    });
                  }, 1000);
                });
              });
            });
            // Example of retrieving a collections indexes using a Promise.
            
            var MongoClient = require('mongodb').MongoClient,
              test = require('assert');
            MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
              // Crete the collection for the distinct example
              var collection = db.collection('simple_key_based_distinct_with_promise');
            
              // Create a geo 2d index
              collection.ensureIndex({loc:"2d"}, {w:1}).then(function(result) {
            
                // Create a simple single field index
                collection.ensureIndex({a:1}, {w:1}).then(function(result) {
            
                  setTimeout(function() {
                    // List all of the indexes on the collection
                    collection.indexes().then(function(indexes) {
                      test.equal(3, indexes.length);
            
                      db.close();
                    });
                  }, 1000);
                });
              });
            });
            // Example of retrieving a collections indexes 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');
              // Crete the collection for the distinct example
              var collection = db.collection('simple_key_based_distinct_with_generators');
            
              // Create a geo 2d index
              yield collection.ensureIndex({loc:"2d"}, {w:1});
            
              // Create a simple single field index
              yield collection.ensureIndex({a:1}, {w:1});
            
              setTimeout(function() {
                co(function*() {
                  // List all of the indexes on the collection
                  var indexes = yield collection.indexes()
                  test.equal(3, indexes.length);
            
                  db.close();
                });
              }, 1000);
            });

            indexExists(indexes, callback){Promise}

            Checks if one or more indexes exist on the collection, fails on first non-existing index

            Name Type Description
            indexes string | array

            One or more index names to check.

            callback Collection~resultCallback optional

            The command result callback

            Returns:
            Promise if no callback passed
            Examples
            // An example showing the use of the indexExists function for a single index name and a list of index names.
            
            var MongoClient = require('mongodb').MongoClient,
              test = require('assert');
            MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
              // Create a test collection that we are getting the options back from
              var collection = db.collection('test_collection_index_exists', {w:1});
              test.equal(null, err);
              // Create an index on the collection
              collection.createIndex('a', {w:1}, function(err, indexName) {
                // Let's test to check if a single index exists
                collection.indexExists("a_1", function(err, result) {
                  test.equal(true, result);
            
                  // Let's test to check if multiple indexes are available
                  collection.indexExists(["a_1", "_id_"], function(err, result) {
                    test.equal(true, result);
            
                    // Check if a non existing index exists
                    collection.indexExists("c_1", function(err, result) {
                      test.equal(false, result);
            
                      db.close();
                    });
                  });
                });
              });
            });
            // An example showing the use of the indexExists function using a Promise for a single index name and a list of index names.
            
            var MongoClient = require('mongodb').MongoClient,
              test = require('assert');
            MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
              // Create a test collection that we are getting the options back from
              var collection = db.collection('test_collection_index_exists_with_promise', {w:1});
              // Create an index on the collection
              collection.createIndex('a', {w:1}).then(function(indexName) {
                // Let's test to check if a single index exists
                collection.indexExists("a_1").then(function(result) {
                  test.equal(true, result);
            
                  // Let's test to check if multiple indexes are available
                  collection.indexExists(["a_1", "_id_"]).then(function(result) {
                    test.equal(true, result);
            
                    // Check if a non existing index exists
                    collection.indexExists("c_1").then(function(result) {
                      test.equal(false, result);
            
                      db.close();
                    });
                  });
                });
              });
            });
            // An example showing the use of the indexExists function using a Generator and the co module for a single index name and a list of index names.
            
            var MongoClient = require('mongodb').MongoClient,
              co = require('co');
              test = require('assert');
            
            co(function*() {
              var db = yield MongoClient.connect('mongodb://localhost:27017/test');
              // Create a test collection that we are getting the options back from
              var collection = db.collection('test_collection_index_exists_with_generators', {w:1});
              // Create an index on the collection
              yield collection.createIndex('a', {w:1});
            
              // Let's test to check if a single index exists
              var result = yield collection.indexExists("a_1");
              test.equal(true, result);
            
              // Let's test to check if multiple indexes are available
              var result = yield collection.indexExists(["a_1", "_id_"]);
              test.equal(true, result);
            
              // Check if a non existing index exists
              var result = yield collection.indexExists("c_1");
              test.equal(false, result);
            
              db.close();
            });

            indexInformation(options, callback){Promise}

            Retrieves this collections index info.

            Name Type Default Description
            options object null optional

            Optional settings.

            Name Type Default Description
            full boolean false optional

            Returns the full raw index information.

            callback Collection~resultCallback optional

            The command result callback

            Returns:
            Promise if no callback passed
            Examples
            // 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 we want to drop later
              var collection = db.collection('more_index_information_test_2');
              // Insert a bunch of documents for the index
              collection.insertMany([{a:1, b:1}
                , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}, function(err, result) {
                test.equal(null, err);
            
                // Create an index on the a field
                collection.ensureIndex({a:1, b:1}
                  , {unique:true, background:true, w:1}, function(err, indexName) {
                  test.equal(null, err);
                  // Fetch basic indexInformation for collection
                  db.indexInformation('more_index_information_test_2', function(err, indexInformation) {
                    test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_);
                    test.deepEqual([ [ 'a', 1 ], [ 'b', 1 ] ], indexInformation.a_1_b_1);
            
                    // Fetch full index information
                    collection.indexInformation({full:true}, function(err, indexInformation) {
                      test.deepEqual({ _id: 1 }, indexInformation[0].key);
                      test.deepEqual({ a: 1, b: 1 }, indexInformation[1].key);
            
                      db.close();
                    });
                  });
                });
              });
            });
            // An examples 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 we want to drop later
              var collection = db.collection('more_index_information_test_3');
              // Insert a bunch of documents for the index
              collection.insertMany([{a:1, b:1}
                , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}, function(err, result) {
                test.equal(null, err);
            
                // Create an index on the a field
                collection.ensureIndex({a:1, b:1}
                  , {unique:true, background:true, w:1}, function(err, indexName) {
                  test.equal(null, err);
            
                  // Fetch basic indexInformation for collection
                  collection.indexInformation(function(err, indexInformation) {
                    test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_);
                    test.deepEqual([ [ 'a', 1 ], [ 'b', 1 ] ], indexInformation.a_1_b_1);
            
                    // Fetch full index information
                    collection.indexInformation({full:true}, function(err, indexInformation) {
                      test.deepEqual({ _id: 1 }, indexInformation[0].key);
                      test.deepEqual({ a: 1, b: 1 }, indexInformation[1].key);
            
                      db.close();
                    });
                  });
                });
              });
            });
            // An example showing the information returned by indexInformation using a Promise.
            
            var MongoClient = require('mongodb').MongoClient,
              test = require('assert');
            MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
            
              // Create a collection we want to drop later
              var collection = db.collection('more_index_information_test_2_with_promise');
              // Insert a bunch of documents for the index
              collection.insertMany([{a:1, b:1}
                , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}).then(function(result) {
            
                // Create an index on the a field
                collection.ensureIndex({a:1, b:1}
                  , {unique:true, background:true, w:1}).then(function(indexName) {
                  // Fetch basic indexInformation for collection
                  db.indexInformation('more_index_information_test_2_with_promise').then(function(indexInformation) {
                    test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_);
                    test.deepEqual([ [ 'a', 1 ], [ 'b', 1 ] ], indexInformation.a_1_b_1);
            
                    // Fetch full index information
                    collection.indexInformation({full:true}).then(function(indexInformation) {
                      test.deepEqual({ _id: 1 }, indexInformation[0].key);
                      test.deepEqual({ a: 1, b: 1 }, indexInformation[1].key);
            
                      db.close();
                    });
                  }).catch(function(err) {
                    console.dir(err)
                  });
                });
              }).catch(function(err) {
                console.dir(err)
              });
            });
            // An examples showing the information returned by indexInformation using a Promise.
            
            var MongoClient = require('mongodb').MongoClient,
              test = require('assert');
            MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
            
              // Create a collection we want to drop later
              var collection = db.collection('more_index_information_test_3_with_promise');
              // Insert a bunch of documents for the index
              collection.insertMany([{a:1, b:1}
                , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}).then(function(result) {
            
                // Create an index on the a field
                collection.ensureIndex({a:1, b:1}
                  , {unique:true, background:true, w:1}).then(function(indexName) {
            
                  // Fetch basic indexInformation for collection
                  collection.indexInformation().then(function(indexInformation) {
                    test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_);
                    test.deepEqual([ [ 'a', 1 ], [ 'b', 1 ] ], indexInformation.a_1_b_1);
            
                    // Fetch full index information
                    collection.indexInformation({full:true}).then(function(indexInformation) {
                      test.deepEqual({ _id: 1 }, indexInformation[0].key);
                      test.deepEqual({ a: 1, b: 1 }, indexInformation[1].key);
            
                      db.close();
                    });
                  });
                });
              });
            });
            // An example showing the information returned by indexInformation 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');
            
              // Create a collection we want to drop later
              var collection = db.collection('more_index_information_test_2_with_generators');
              // Insert a bunch of documents for the index
              yield collection.insertMany([{a:1, b:1}
                , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1});
            
              // Create an index on the a field
              yield collection.ensureIndex({a:1, b:1}
                , {unique:true, background:true, w:1});
            
              // Fetch basic indexInformation for collection
              var indexInformation = yield db.indexInformation('more_index_information_test_2_with_generators');
              test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_);
              test.deepEqual([ [ 'a', 1 ], [ 'b', 1 ] ], indexInformation.a_1_b_1);
            
              // Fetch full index information
              var indexInformation = yield collection.indexInformation({full:true});
              test.deepEqual({ _id: 1 }, indexInformation[0].key);
              test.deepEqual({ a: 1, b: 1 }, indexInformation[1].key);
            
              // Close db
              db.close();
            });
            // An examples showing the information returned by indexInformation 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');
            
              // Create a collection we want to drop later
              var collection = db.collection('more_index_information_test_3_with_generators');
              // Insert a bunch of documents for the index
              yield collection.insertMany([{a:1, b:1}
                , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1});
            
              // Create an index on the a field
              yield collection.ensureIndex({a:1, b:1}
                , {unique:true, background:true, w:1});
            
              // Fetch basic indexInformation for collection
              var indexInformation = yield collection.indexInformation();
              test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_);
              test.deepEqual([ [ 'a', 1 ], [ 'b', 1 ] ], indexInformation.a_1_b_1);
            
              // Fetch full index information
              var indexInformation = yield collection.indexInformation({full:true});
              test.deepEqual({ _id: 1 }, indexInformation[0].key);
              test.deepEqual({ a: 1, b: 1 }, indexInformation[1].key);
            
              db.close();
            });

            initializeOrderedBulkOp(options, callback){null}

            Initiate an In order bulk write operation, operations will be serially executed in the order they are added, creating a new operation for each switch in types.

            Name Type Default Description
            options object null optional

            Optional settings.

            Name Type Default Description
            w number | string null optional

            The write concern.

            wtimeout number null optional

            The write concern timeout.

            j boolean false optional

            Specify a journal write concern.

            callback OrderedBulkOperation

            The command result callback

            Examples
            // Example of a simple ordered insert/update/upsert/remove ordered collection
            
            var MongoClient = require('mongodb').MongoClient,
              test = require('assert');
            MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
              // Get the collection
              var col = db.collection('batch_write_ordered_ops_0');
              // Initialize the Ordered Batch
              var batch = col.initializeOrderedBulkOp();
              // Add some operations to be executed in order
              batch.insert({a:1});
              batch.find({a:1}).updateOne({$set: {b:1}});
              batch.find({a:2}).upsert().updateOne({$set: {b:2}});
              batch.insert({a:3});
              batch.find({a:3}).remove({a:3});
            
              // Execute the operations
              batch.execute(function(err, result) {
                // Check state of result
                test.equal(2, result.nInserted);
                test.equal(1, result.nUpserted);
                test.equal(1, result.nMatched);
                test.ok(1 == result.nModified || result.nModified == null);
                test.equal(1, result.nRemoved);
            
                var upserts = result.getUpsertedIds();
                test.equal(1, upserts.length);
                test.equal(2, upserts[0].index);
                test.ok(upserts[0]._id != null);
            
                var upsert = result.getUpsertedIdAt(0);
                test.equal(2, upsert.index);
                test.ok(upsert._id != null);
            
                // Finish up test
                db.close();
              });
            });
            // Example of a simple ordered insert/update/upsert/remove ordered collection using a Promise.
            
            var MongoClient = require('mongodb').MongoClient,
              test = require('assert');
            MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
              // Get the collection
              var col = db.collection('batch_write_ordered_ops_0_with_promise');
              // Initialize the Ordered Batch
              var batch = col.initializeOrderedBulkOp();
              // Add some operations to be executed in order
              batch.insert({a:1});
              batch.find({a:1}).updateOne({$set: {b:1}});
              batch.find({a:2}).upsert().updateOne({$set: {b:2}});
              batch.insert({a:3});
              batch.find({a:3}).remove({a:3});
            
              // Execute the operations
              batch.execute().then(function(result) {
                // Check state of result
                test.equal(2, result.nInserted);
                test.equal(1, result.nUpserted);
                test.equal(1, result.nMatched);
                test.ok(1 == result.nModified || result.nModified == 0 || result.nModified == null);
                test.equal(1, result.nRemoved);
            
                var upserts = result.getUpsertedIds();
                test.equal(1, upserts.length);
                test.equal(2, upserts[0].index);
                test.ok(upserts[0]._id != null);
            
                var upsert = result.getUpsertedIdAt(0);
                test.equal(2, upsert.index);
                test.ok(upsert._id != null);
            
                // Finish up test
                db.close();
              });
            });
            // Example of a simple ordered insert/update/upsert/remove ordered collection 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');
              // Get the collection
              var col = db.collection('batch_write_ordered_ops_0_with_generators');
              // Initialize the Ordered Batch
              var batch = col.initializeOrderedBulkOp();
              // Add some operations to be executed in order
              batch.insert({a:1});
              batch.find({a:1}).updateOne({$set: {b:1}});
              batch.find({a:2}).upsert().updateOne({$set: {b:2}});
              batch.insert({a:3});
              batch.find({a:3}).remove({a:3});
            
              // Execute the operations
              var result = yield batch.execute();
              // Check state of result
              test.equal(2, result.nInserted);
              test.equal(1, result.nUpserted);
              test.equal(1, result.nMatched);
              test.ok(1 == result.nModified || result.nModified == null);
              test.equal(1, result.nRemoved);
            
              var upserts = result.getUpsertedIds();
              test.equal(1, upserts.length);
              test.equal(2, upserts[0].index);
              test.ok(upserts[0]._id != null);
            
              var upsert = result.getUpsertedIdAt(0);
              test.equal(2, upsert.index);
              test.ok(upsert._id != null);
            
              // Finish up test
              db.close();
            });

            initializeUnorderedBulkOp(options){UnorderedBulkOperation}

            Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.

            Name Type Default Description
            options object null optional

            Optional settings.

            Name Type Default Description
            w number | string null optional

            The write concern.

            wtimeout number null optional

            The write concern timeout.

            j boolean false optional

            Specify a journal write concern.

            Examples
            // Example of a simple ordered insert/update/upsert/remove ordered collection
            
            var MongoClient = require('mongodb').MongoClient,
              test = require('assert');
            MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
              // Get the collection
              var col = db.collection('batch_write_unordered_ops_legacy_0');
              // Initialize the unordered Batch
              var batch = col.initializeUnorderedBulkOp();
            
              // Add some operations to be executed in order
              batch.insert({a:1});
              batch.find({a:1}).updateOne({$set: {b:1}});
              batch.find({a:2}).upsert().updateOne({$set: {b:2}});
              batch.insert({a:3});
              batch.find({a:3}).remove({a:3});
            
              // Execute the operations
              batch.execute(function(err, result) {
                // Check state of result
                test.equal(2, result.nInserted);
                test.equal(1, result.nUpserted);
                test.equal(1, result.nMatched);
                test.ok(1 == result.nModified || result.nModified == null);
                test.equal(1, result.nRemoved);
            
                var upserts = result.getUpsertedIds();
                test.equal(1, upserts.length);
                test.equal(2, upserts[0].index);
                test.ok(upserts[0]._id != null);
            
                var upsert = result.getUpsertedIdAt(0);
                test.equal(2, upsert.index);
                test.ok(upsert._id != null);
            
                // Finish up test
                db.close();
              });
            });
            // Example of a simple ordered insert/update/upsert/remove ordered collection using a Promise.
            
            var MongoClient = require('mongodb').MongoClient,
              test = require('assert');
            MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
              // Get the collection
              var col = db.collection('batch_write_unordered_ops_legacy_0_with_promise');
              // Initialize the unordered Batch
              var batch = col.initializeUnorderedBulkOp();
            
              // Add some operations to be executed in order
              batch.insert({a:1});
              batch.find({a:1}).updateOne({$set: {b:1}});
              batch.find({a:2}).upsert().updateOne({$set: {b:2}});
              batch.insert({a:3});
              batch.find({a:3}).remove({a:3});
            
              // Execute the operations
              batch.execute().then(function(result) {
                // Check state of result
                test.equal(2, result.nInserted);
                test.equal(1, result.nUpserted);
                test.equal(1, result.nMatched);
                test.ok(1 == result.nModified || result.nModified == 0 || result.nModified == null);
                test.equal(1, result.nRemoved);
            
                var upserts = result.getUpsertedIds();
                test.equal(1, upserts.length);
                test.equal(2, upserts[0].index);
                test.ok(upserts[0]._id != null);
            
                var upsert = result.getUpsertedIdAt(0);
                test.equal(2, upsert.index);
                test.ok(upsert._id != null);
            
                // Finish up test
                db.close();
              });
            });
            // Example of a simple ordered insert/update/upsert/remove ordered collection 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');
              // Get the collection
              var col = db.collection('batch_write_unordered_ops_legacy_0_with_generators');
              // Initialize the unordered Batch
              var batch = col.initializeUnorderedBulkOp({useLegacyOps: true});
            
              // Add some operations to be executed in order
              batch.insert({a:1});
              batch.find({a:1}).updateOne({$set: {b:1}});
              batch.find({a:2}).upsert().updateOne({$set: {b:2}});
              batch.insert({a:3});
              batch.find({a:3}).remove({a:3});
            
              // Execute the operations
              var result = yield batch.execute();
              // Check state of result
              test.equal(2, result.nInserted);
              test.equal(1, result.nUpserted);
              test.equal(1, result.nMatched);
              test.ok(1 == result.nModified || result.nModified == null);
              test.equal(1, result.nRemoved);
            
              var upserts = result.getUpsertedIds();
              test.equal(1, upserts.length);
              test.equal(2, upserts[0].index);
              test.ok(upserts[0]._id != null);
            
              var upsert = result.getUpsertedIdAt(0);
              test.equal(2, upsert.index);
              test.ok(upsert._id != null);
            
              // Finish up test
              db.close();
            });

            insert(docs, options, callback){Promise}

            Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the _id field,
            one will be added to each of the documents missing it by the driver, mutating the document. This behavior
            can be overridden by setting the forceServerObjectId flag.

            Name Type Default Description
            docs object | Array.<object>

            Documents to insert.

            options object null optional

            Optional settings.

            Name Type Default Description
            w number | string null optional

            The write concern.

            wtimeout number null optional

            The write concern timeout.

            j boolean false optional

            Specify a journal write concern.

            serializeFunctions boolean false optional

            Serialize functions on any object.

            forceServerObjectId boolean false optional

            Force server to assign _id values instead of driver.

            bypassDocumentValidation boolean false optional

            Allow driver to bypass schema validation in MongoDB 3.2 or higher.

            callback Collection~insertWriteOpCallback optional

            The command result callback

            Deprecated
            • Use insertOne, insertMany or bulkWrite
              Returns:
              Promise if no callback passed
              Examples
              // A simple document insert example, not using safe mode to ensure document persistance on MongoDB
              
              var MongoClient = require('mongodb').MongoClient,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                var collection = db.collection("simple_document_insert_collection_no_safe");
                // Insert a single document
                collection.insertOne({hello:'world_no_safe'});
              
                // Wait for a second before finishing up, to ensure we have written the item to disk
                setTimeout(function() {
              
                  // Fetch the document
                  collection.findOne({hello:'world_no_safe'}, function(err, item) {
                    test.equal(null, err);
                    test.equal('world_no_safe', item.hello);
                    db.close();
                  })
                }, 100);
              });
              // A batch document insert example, using safe mode to ensure document persistance on MongoDB
              
              var MongoClient = require('mongodb').MongoClient,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                // Fetch a collection to insert document into
                var collection = db.collection("batch_document_insert_collection_safe");
                // Insert a single document
                collection.insertMany([{hello:'world_safe1'}
                  , {hello:'world_safe2'}], {w:1}, function(err, result) {
                  test.equal(null, err);
              
                  // Fetch the document
                  collection.findOne({hello:'world_safe2'}, function(err, item) {
                    test.equal(null, err);
                    test.equal('world_safe2', item.hello);
                    db.close();
                  })
                });
              });
              // Example of inserting a document containing functions
              
              var MongoClient = require('mongodb').MongoClient,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                // Fetch a collection to insert document into
                var collection = db.collection("simple_document_insert_with_function_safe");
              
                var o = {w:1};
                o.serializeFunctions = true;
                // Insert a single document
                collection.insertOne({hello:'world'
                  , func:function() {}}, o, function(err, result) {
                  test.equal(null, err);
              
                  // Fetch the document
                  collection.findOne({hello:'world'}, function(err, item) {
                    test.equal(null, err);
                    test.ok("function() {}", item.code);
                    db.close();
                  })
                });
              });
              // Example of using keepGoing to allow batch insert to complete even when there are illegal documents in the batch
              
              var MongoClient = require('mongodb').MongoClient,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
              
                // Create a collection
                var collection = db.collection('keepGoingExample');
              
                // Add an unique index to title to force errors in the batch insert
                collection.ensureIndex({title:1}, {unique:true}, function(err, indexName) {
              
                  // Insert some intial data into the collection
                  collection.insertMany([{name:"Jim"}
                    , {name:"Sarah", title:"Princess"}], {w:1}, function(err, result) {
              
                    // Force keep going flag, ignoring unique index issue
                    collection.insert([{name:"Jim"}
                      , {name:"Sarah", title:"Princess"}
                      , {name:'Gump', title:"Gump"}], {w:1, keepGoing:true}, function(err, result) {
              
                      // Count the number of documents left (should not include the duplicates)
                      collection.count(function(err, count) {
                        test.equal(3, count);
                        db.close();
                      })
                    });
                  });
                });
              });
              // A simple document insert using a Promise example, not using safe mode to ensure document persistance on MongoDB
              
              var MongoClient = require('mongodb').MongoClient,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                var collection = db.collection("simple_document_insert_collection_no_safe_with_promise");
                // Insert a single document
                collection.insertOne({hello:'world_no_safe'});
              
                // Wait for a second before finishing up, to ensure we have written the item to disk
                setTimeout(function() {
              
                  // Fetch the document
                  collection.findOne({hello:'world_no_safe'}).then(function(item) {
                    test.equal('world_no_safe', item.hello);
                    db.close();
                  })
                }, 100);
              });
              // A batch document insert using a Promise example, using safe mode to ensure document persistance on MongoDB
              
              var MongoClient = require('mongodb').MongoClient,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                // Fetch a collection to insert document into
                var collection = db.collection("batch_document_insert_collection_safe_with_promise");
                // Insert a single document
                collection.insertMany([{hello:'world_safe1'}
                  , {hello:'world_safe2'}], {w:1}).then(function(result) {
              
                  // Fetch the document
                  collection.findOne({hello:'world_safe2'}).then(function(item) {
                    test.equal('world_safe2', item.hello);
                    db.close();
                  })
                });
              });
              // Example of inserting a document containing functions using a Promise.
              
              var MongoClient = require('mongodb').MongoClient,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                // Fetch a collection to insert document into
                var collection = db.collection("simple_document_insert_with_function_safe_with_promise");
              
                var o = {w:1};
                o.serializeFunctions = true;
                // Insert a single document
                collection.insertOne({hello:'world'
                  , func:function() {}}, o).then(function(result) {
              
                  // Fetch the document
                  collection.findOne({hello:'world'}).then(function(item) {
                    test.ok("function() {}", item.code);
                    db.close();
                  })
                });
              });
              // Example of using keepGoing to allow batch insert using a Promise to complete even when there are illegal documents in the batch
              
              var MongoClient = require('mongodb').MongoClient,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
              
                // Create a collection
                var collection = db.collection('keepGoingExample_with_promise');
                collection.drop(function() {
                  // Add an unique index to title to force errors in the batch insert
                  collection.ensureIndex({title:1}, {unique:true}).then(function(indexName) {
              
                    // Insert some intial data into the collection
                    collection.insertMany([{name:"Jim"}
                      , {name:"Sarah", title:"Princess"}], {w:1}).then(function(result) {
              
                      // Force keep going flag, ignoring unique index issue
                      collection.insert([{name:"Jim"}
                        , {name:"Sarah", title:"Princess"}
                        , {name:'Gump', title:"Gump"}], {w:1, keepGoing:true}).then(function(result) {
                        }).catch(function(err) {
                        // Count the number of documents left (should not include the duplicates)
                        collection.count().then(function(count) {
                          test.equal(3, count);
                        })
                      });
                    });
                  });
                });
              });
              // A simple document insert using a Generator and the co module example, not using safe mode to ensure document persistance on MongoDB
              
              var MongoClient = require('mongodb').MongoClient,
                co = require('co');
                test = require('assert');
              
              co(function*() {
                var db = yield MongoClient.connect('mongodb://localhost:27017/test');
                var collection = db.collection("simple_document_insert_collection_no_safe_with_generators");
                // Insert a single document
                collection.insertOne({hello:'world_no_safe'});
              
                // Wait for a second before finishing up, to ensure we have written the item to disk
                setTimeout(function() {
                  co(function*() {
                    // Fetch the document
                    var item = yield collection.findOne({hello:'world_no_safe'});
                    test.equal('world_no_safe', item.hello);
                    db.close();
                  })
                }, 100);
              });
              // A batch document insert using a Generator and the co module example, using safe mode to ensure document persistance on MongoDB
              
              var MongoClient = require('mongodb').MongoClient,
                co = require('co');
                test = require('assert');
              
              co(function*() {
                var db = yield MongoClient.connect('mongodb://localhost:27017/test');
                // Fetch a collection to insert document into
                var collection = db.collection("batch_document_insert_collection_safe_with_generators");
              
                // Insert a single document
                yield collection.insertMany([{hello:'world_safe1'}
                  , {hello:'world_safe2'}], {w:1});
              
                // Fetch the document
                var item = yield collection.findOne({hello:'world_safe2'});
                test.equal('world_safe2', item.hello);
                db.close();
              });
              // Example of inserting a document containing functions 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');
                // Fetch a collection to insert document into
                var collection = db.collection("simple_document_insert_with_function_safe_with_generators");
              
                // Get the option
                var o = {w:1};
                o.serializeFunctions = true;
              
                // Insert a single document
                yield collection.insertOne({hello:'world', func:function() {}}, o);
              
                // Fetch the document
                var item = yield collection.findOne({hello:'world'});
                test.ok("function() {}", item.code);
                db.close();
              });
              // Example of using keepGoing to allow batch insert using a Generator and the co module to complete even when there are illegal documents in the batch
              
              var MongoClient = require('mongodb').MongoClient,
                co = require('co');
                test = require('assert');
              
              co(function*() {
                var db = yield MongoClient.connect('mongodb://localhost:27017/test');
              
                // Create a collection
                var collection = db.collection('keepGoingExample_with_generators');
              
                // Add an unique index to title to force errors in the batch insert
                yield collection.ensureIndex({title:1}, {unique:true});
              
                // Insert some intial data into the collection
                yield collection.insertMany([{name:"Jim"}
                  , {name:"Sarah", title:"Princess"}], {w:1});
              
                try {
                  // Force keep going flag, ignoring unique index issue
                  yield collection.insert([{name:"Jim"}
                    , {name:"Sarah", title:"Princess"}
                    , {name:'Gump', title:"Gump"}], {w:1, keepGoing:true});
                } catch(err) {}
                // Count the number of documents left (should not include the duplicates)
                var count = yield collection.count();
                test.equal(3, count);
              }).catch(function(err) {
                console.log(err.stack)
              });

              insertMany(docs, options, callback){Promise}

              Inserts an array of documents into MongoDB. If documents passed in do not contain the _id field,
              one will be added to each of the documents missing it by the driver, mutating the document. This behavior
              can be overridden by setting the forceServerObjectId flag.

              Name Type Default Description
              docs Array.<object>

              Documents to insert.

              options object null optional

              Optional settings.

              Name Type Default Description
              w number | string null optional

              The write concern.

              wtimeout number null optional

              The write concern timeout.

              j boolean false optional

              Specify a journal write concern.

              serializeFunctions boolean false optional

              Serialize functions on any object.

              forceServerObjectId boolean false optional

              Force server to assign _id values instead of driver.

              bypassDocumentValidation boolean false optional

              Allow driver to bypass schema validation in MongoDB 3.2 or higher.

              ordered boolean true optional

              If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails.

              callback Collection~insertWriteOpCallback optional

              The command result callback

              Returns:
              Promise if no callback passed
              Examples
              // Example of a simple insertMany operation
              
              var MongoClient = require('mongodb').MongoClient,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                // Get the collection
                var col = db.collection('insert_many');
                col.insertMany([{a:1}, {a:2}], function(err, r) {
                  test.equal(null, err);
                  test.equal(2, r.insertedCount);
                  // Finish up test
                  db.close();
                });
              });
              // Example of a simple insertMany operation using a Promise.
              
              var MongoClient = require('mongodb').MongoClient,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                // Get the collection
                var col = db.collection('insert_many_with_promise');
                col.insertMany([{a:1}, {a:2}]).then(function(r) {
                  test.equal(2, r.insertedCount);
                  // Finish up test
                  db.close();
                });
              });
              // Example of a simple insertMany operation 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');
                // Get the collection
                var col = db.collection('insert_many_with_generators');
                var r = yield col.insertMany([{a:1}, {a:2}]);
                test.equal(2, r.insertedCount);
                // Finish up test
                db.close();
              });

              insertOne(doc, options, callback){Promise}

              Inserts a single document into MongoDB. If documents passed in do not contain the _id field,
              one will be added to each of the documents missing it by the driver, mutating the document. This behavior
              can be overridden by setting the forceServerObjectId flag.

              Name Type Default Description
              doc object

              Document to insert.

              options object null optional

              Optional settings.

              Name Type Default Description
              w number | string null optional

              The write concern.

              wtimeout number null optional

              The write concern timeout.

              j boolean false optional

              Specify a journal write concern.

              serializeFunctions boolean false optional

              Serialize functions on any object.

              forceServerObjectId boolean false optional

              Force server to assign _id values instead of driver.

              bypassDocumentValidation boolean false optional

              Allow driver to bypass schema validation in MongoDB 3.2 or higher.

              callback Collection~insertOneWriteOpCallback optional

              The command result callback

              Returns:
              Promise if no callback passed
              Examples
              // Example of a simple insertOne operation
              
              var MongoClient = require('mongodb').MongoClient,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                // Get the collection
                var col = db.collection('insert_one');
                col.insertOne({a:1}, function(err, r) {
                  test.equal(null, err);
                  test.equal(1, r.insertedCount);
                  // Finish up test
                  db.close();
                });
              });
              // Example of a simple insertOne operation using a Promise.
              
              var MongoClient = require('mongodb').MongoClient,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                // Get the collection
                var col = db.collection('insert_one_with_promise');
                col.insertOne({a:1}).then(function(r) {
                  test.equal(1, r.insertedCount);
                  // Finish up test
                  db.close();
                });
              });
              // Example of a simple insertOne operation 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');
                // Get the collection
                var col = db.collection('insert_one_with_generators');
                var r = yield col.insertOne({a:1});
                test.equal(1, r.insertedCount);
                // Finish up test
                db.close();
              });

              isCapped(callback){Promise}

              Returns if the collection is a capped collection

              Name Type Description
              callback Collection~resultCallback optional

              The results callback

              Returns:
              Promise if no callback passed
              Examples
              // An example showing how to establish if it's a capped collection
              
              var MongoClient = require('mongodb').MongoClient,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
              
                // Create a test collection that we are getting the options back from
                db.createCollection('test_collection_is_capped', {'capped':true, 'size':1024}, function(err, collection) {
                  test.equal('test_collection_is_capped', collection.collectionName);
              
                  // Let's fetch the collection options
                  collection.isCapped(function(err, capped) {
                    test.equal(true, capped);
              
                    db.close();
                  });
                });
              });
              // An example showing how to establish if it's a capped collection using a Promise.
              
              var MongoClient = require('mongodb').MongoClient,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
              
                // Create a test collection that we are getting the options back from
                db.createCollection('test_collection_is_capped_with_promise', {'capped':true, 'size':1024}).then(function(collection) {
                  test.equal('test_collection_is_capped_with_promise', collection.collectionName);
              
                  // Let's fetch the collection options
                  collection.isCapped().then(function(capped) {
                    test.equal(true, capped);
              
                    db.close();
                  });
                });
              });
              // An example showing how to establish if it's a capped collection 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');
              
                // Create a test collection that we are getting the options back from
                var collection = yield db.createCollection('test_collection_is_capped_with_generators', {'capped':true, 'size':1024});
                test.equal('test_collection_is_capped_with_generators', collection.collectionName);
              
                // Let's fetch the collection options
                var capped = yield collection.isCapped();
                test.equal(true, capped);
              
                db.close();
              });

              listIndexes(options){CommandCursor}

              Get the list of all indexes information for the collection.

              Name Type Default Description
              options object null optional

              Optional settings.

              Name Type Default Description
              batchSize number null optional

              The batchSize for the returned command cursor or if pre 2.8 the systems batch collection

              readPreference ReadPreference | string null optional

              The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).

              mapReduce(map, reduce, options, callback){Promise}

              Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection.

              Name Type Default Description
              map function | string

              The mapping function.

              reduce function | string

              The reduce function.

              options object null optional

              Optional settings.

              Name Type Default Description
              readPreference ReadPreference | string null optional

              The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).

              out object null optional

              Sets the output target for the map reduce job. {inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}

              query object null optional

              Query filter object.

              sort object null optional

              Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces.

              limit number null optional

              Number of objects to return from collection.

              keeptemp boolean false optional

              Keep temporary data.

              finalize function | string null optional

              Finalize function.

              scope object null optional

              Can pass in variables that can be access from map/reduce/finalize.

              jsMode boolean false optional

              It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X.

              verbose boolean false optional

              Provide statistics on job execution time.

              bypassDocumentValidation boolean false optional

              Allow driver to bypass schema validation in MongoDB 3.2 or higher.

              callback Collection~resultCallback optional

              The command result callback

              Throws:
              Returns:
              Promise if no callback passed
              Examples
              // A simple map reduce example
              
              var MongoClient = require('mongodb').MongoClient,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
              
                // Create a test collection
                var collection = db.collection('test_map_reduce_functions');
              
                // Insert some documents to perform map reduce over
                collection.insertMany([{'user_id':1}, {'user_id':2}], {w:1}, function(err, r) {
              
                  // Map function
                  var map = function() { emit(this.user_id, 1); };
                  // Reduce function
                  var reduce = function(k,vals) { return 1; };
              
                  // Perform the map reduce
                  collection.mapReduce(map, reduce, {out: {replace : 'tempCollection'}}, function(err, collection) {
                    test.equal(null, err);
              
                    // Mapreduce returns the temporary collection with the results
                    collection.findOne({'_id':1}, function(err, result) {
                      test.equal(1, result.value);
              
                      collection.findOne({'_id':2}, function(err, result) {
                        test.equal(1, result.value);
              
                        db.close();
                      });
                    });
                  });
                });
              });
              // A simple map reduce example using the inline output type on MongoDB > 1.7.6 returning the statistics
              
              var MongoClient = require('mongodb').MongoClient,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
              
                // Create a test collection
                var collection = db.collection('test_map_reduce_functions_inline');
              
                // Insert some test documents
                collection.insertMany([{'user_id':1}, {'user_id':2}], {w:1}, function(err, r) {
              
                  // Map function
                  var map = function() { emit(this.user_id, 1); };
                  // Reduce function
                  var reduce = function(k,vals) { return 1; };
              
                  // Execute map reduce and return results inline
                  collection.mapReduce(map, reduce, {out : {inline: 1}, verbose:true}, function(err, results, stats) {
                    test.equal(2, results.length);
                    test.ok(stats != null);
              
                    collection.mapReduce(map, reduce, {out : {replace: 'mapreduce_integration_test'}, verbose:true}, function(err, results, stats) {
                      test.ok(stats != null);
                      db.close();
                    });
                  });
                });
              });
              // Mapreduce different test with a provided scope containing a javascript function.
              
              var MongoClient = require('mongodb').MongoClient,
                Code = require('mongodb').Code,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
              
                // Create a test collection
                var collection = db.collection('test_map_reduce_functions_scope');
              
                // Insert some test documents
                collection.insertMany([{'user_id':1, 'timestamp':new Date()}
                  , {'user_id':2, 'timestamp':new Date()}], {w:1}, function(err, r) {
              
                  // Map function
                  var map = function(){
                      emit(fn(this.timestamp.getYear()), 1);
                  }
              
                  // Reduce function
                  var reduce = function(k, v){
                      count = 0;
                      for(i = 0; i < v.length; i++) {
                          count += v[i];
                      }
                      return count;
                  }
              
                  // Javascript function available in the map reduce scope
                  var t = function(val){ return val+1; }
              
                  // Execute the map reduce with the custom scope
                  var o = {};
                  o.scope =  { fn: new Code(t.toString()) }
                  o.out = { replace: 'replacethiscollection' }
              
                  collection.mapReduce(map, reduce, o, function(err, outCollection) {
                    test.equal(null, err);
              
                    // Find all entries in the map-reduce collection
                    outCollection.find().toArray(function(err, results) {
                      test.equal(null, err);
                      test.equal(2, results[0].value)
              
                      // mapReduce with scope containing plain function
                      var o = {};
                      o.scope =  { fn: t }
                      o.out = { replace: 'replacethiscollection' }
              
                      collection.mapReduce(map, reduce, o, function(err, outCollection) {
                        test.equal(null, err);
              
                        // Find all entries in the map-reduce collection
                        outCollection.find().toArray(function(err, results) {
                          test.equal(2, results[0].value)
              
                          db.close();
                        });
                      });
                    });
                  });
                });
              });
              // Mapreduce different test with a provided scope containing javascript objects with functions.
              
              var MongoClient = require('mongodb').MongoClient,
                Code = require('mongodb').Code,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
              
                // Create a test collection
                var collection = db.collection('test_map_reduce_functions_scope_objects');
              
                // Insert some test documents
                collection.insertMany([{'user_id':1, 'timestamp':new Date()}
                  , {'user_id':2, 'timestamp':new Date()}], {w:1}, function(err, r) {
              
                  // Map function
                  var map = function(){
                    emit(obj.fn(this.timestamp.getYear()), 1);
                  }
              
                  // Reduce function
                  var reduce = function(k, v){
                    count = 0;
                    for(i = 0; i < v.length; i++) {
                      count += v[i];
                    }
                    return count;
                  }
              
                  // Javascript function available in the map reduce scope
                  var t = function(val){ return val+1; }
              
                  // Execute the map reduce with the custom scope containing objects
                  var o = {};
                  o.scope =  { obj: {fn: new Code(t.toString())} }
                  o.out = { replace: 'replacethiscollection' }
              
                  collection.mapReduce(map, reduce, o, function(err, outCollection) {
                    test.equal(null, err);
              
                    // Find all entries in the map-reduce collection
                    outCollection.find().toArray(function(err, results) {
                      test.equal(null, err);
                      test.equal(2, results[0].value)
              
                      // mapReduce with scope containing plain function
                      var o = {};
                      o.scope =  { obj: {fn: t} }
                      o.out = { replace: 'replacethiscollection' }
              
                      collection.mapReduce(map, reduce, o, function(err, outCollection) {
                        test.equal(null, err);
              
                        // Find all entries in the map-reduce collection
                        outCollection.find().toArray(function(err, results) {
                          test.equal(2, results[0].value)
                          db.close();
                        });
                      });
                    });
                  });
                });
              });
              // A simple map reduce example using a Promise.
              
              var MongoClient = require('mongodb').MongoClient,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
              
                // Create a test collection
                var collection = db.collection('test_map_reduce_functions_with_promise');
              
                // Insert some documents to perform map reduce over
                collection.insertMany([{'user_id':1}, {'user_id':2}], {w:1}).then(function(r) {
              
                  // Map function
                  var map = function() { emit(this.user_id, 1); };
                  // Reduce function
                  var reduce = function(k,vals) { return 1; };
              
                  // Perform the map reduce
                  collection.mapReduce(map, reduce, {out: {replace : 'tempCollection'}}).then(function(collection) {
              
                    // Mapreduce returns the temporary collection with the results
                    collection.findOne({'_id':1}).then(function(result) {
                      test.equal(1, result.value);
              
                      collection.findOne({'_id':2}).then(function(result) {
                        test.equal(1, result.value);
              
                        db.close();
                      });
                    });
                  });
                });
              });
              // A simple map reduce example using the inline output type on MongoDB > 1.7.6 returning the statistics using a Promise.
              
              var MongoClient = require('mongodb').MongoClient,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
              
                // Create a test collection
                var collection = db.collection('test_map_reduce_functions_inline_with_promise');
              
                // Insert some test documents
                collection.insertMany([{'user_id':1}, {'user_id':2}], {w:1}).then(function(r) {
              
                  // Map function
                  var map = function() { emit(this.user_id, 1); };
                  // Reduce function
                  var reduce = function(k,vals) { return 1; };
              
                  // Execute map reduce and return results inline
                  collection.mapReduce(map, reduce, {out : {inline: 1}, verbose:true}).then(function(result) {
                    test.equal(2, result.results.length);
                    test.ok(result.stats != null);
              
                    collection.mapReduce(map, reduce, {out : {replace: 'mapreduce_integration_test'}, verbose:true}).then(function(result) {
                      test.ok(result.stats != null);
                      db.close();
                    });
                  });
                });
              });
              // Mapreduce using a provided scope containing a javascript function executed using a Promise.
              
              var MongoClient = require('mongodb').MongoClient,
                Code = require('mongodb').Code,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
              
                // Create a test collection
                var collection = db.collection('test_map_reduce_functions_scope_with_promise');
              
                // Insert some test documents
                collection.insertMany([{'user_id':1, 'timestamp':new Date()}
                  , {'user_id':2, 'timestamp':new Date()}], {w:1}).then(function(r) {
              
                  // Map function
                  var map = function(){
                      emit(fn(this.timestamp.getYear()), 1);
                  }
              
                  // Reduce function
                  var reduce = function(k, v){
                      count = 0;
                      for(i = 0; i < v.length; i++) {
                          count += v[i];
                      }
                      return count;
                  }
              
                  // Javascript function available in the map reduce scope
                  var t = function(val){ return val+1; }
              
                  // Execute the map reduce with the custom scope
                  var o = {};
                  o.scope =  { fn: new Code(t.toString()) }
                  o.out = { replace: 'replacethiscollection' }
              
                  collection.mapReduce(map, reduce, o).then(function(outCollection) {
              
                    // Find all entries in the map-reduce collection
                    outCollection.find().toArray().then(function(results) {
                      test.equal(2, results[0].value)
              
                      // mapReduce with scope containing plain function
                      var o = {};
                      o.scope =  { fn: t }
                      o.out = { replace: 'replacethiscollection' }
              
                      collection.mapReduce(map, reduce, o).then(function(outCollection) {
                        // Find all entries in the map-reduce collection
                        outCollection.find().toArray().then(function(results) {
                          test.equal(2, results[0].value)
              
                          db.close();
                        });
                      });
                    });
                  });
                });
              });
              // Mapreduce using a scope containing javascript objects with functions using a Promise.
              
              var MongoClient = require('mongodb').MongoClient,
                Code = require('mongodb').Code,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
              
                // Create a test collection
                var collection = db.collection('test_map_reduce_functions_scope_objects_with_promise');
              
                // Insert some test documents
                collection.insertMany([{'user_id':1, 'timestamp':new Date()}
                  , {'user_id':2, 'timestamp':new Date()}], {w:1}).then(function(r) {
              
                  // Map function
                  var map = function(){
                    emit(obj.fn(this.timestamp.getYear()), 1);
                  }
              
                  // Reduce function
                  var reduce = function(k, v){
                    count = 0;
                    for(i = 0; i < v.length; i++) {
                      count += v[i];
                    }
                    return count;
                  }
              
                  // Javascript function available in the map reduce scope
                  var t = function(val){ return val+1; }
              
                  // Execute the map reduce with the custom scope containing objects
                  var o = {};
                  o.scope =  { obj: {fn: new Code(t.toString())} }
                  o.out = { replace: 'replacethiscollection' }
              
                  collection.mapReduce(map, reduce, o).then(function(outCollection) {
              
                    // Find all entries in the map-reduce collection
                    outCollection.find().toArray().then(function(results) {
                      test.equal(2, results[0].value)
              
                      // mapReduce with scope containing plain function
                      var o = {};
                      o.scope =  { obj: {fn: t} }
                      o.out = { replace: 'replacethiscollection' }
              
                      collection.mapReduce(map, reduce, o).then(function(outCollection) {
                        // Find all entries in the map-reduce collection
                        outCollection.find().toArray().then(function(results) {
                          test.equal(2, results[0].value)
                          db.close();
                        });
                      });
                    });
                  });
                });
              });
              // A simple map reduce example 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');
              
                // Create a test collection
                var collection = db.collection('test_map_reduce_functions_with_generators');
              
                // Insert some documents to perform map reduce over
                yield collection.insertMany([{'user_id':1}, {'user_id':2}], {w:1});
              
                // Map function
                var map = function() { emit(this.user_id, 1); };
                // Reduce function
                var reduce = function(k,vals) { return 1; };
              
                // Perform the map reduce
                var collection = yield collection.mapReduce(map, reduce, {out: {replace : 'tempCollection'}});
              
                // Mapreduce returns the temporary collection with the results
                var result = yield collection.findOne({'_id':1});
                test.equal(1, result.value);
                var result = yield collection.findOne({'_id':2});
                test.equal(1, result.value);
              
                // Db close
                db.close();
              });
              // A simple map reduce example using the inline output type on MongoDB > 1.7.6 returning the statistics 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');
              
                // Create a test collection
                var collection = db.collection('test_map_reduce_functions_inline_with_generators');
              
                // Insert some test documents
                yield collection.insertMany([{'user_id':1}, {'user_id':2}], {w:1});
              
                // Map function
                var map = function() { emit(this.user_id, 1); };
                // Reduce function
                var reduce = function(k,vals) { return 1; };
              
                // Execute map reduce and return results inline
                var result = yield collection.mapReduce(map, reduce, {out : {inline: 1}, verbose:true});
                test.equal(2, result.results.length);
                test.ok(result.stats != null);
              
                var result = yield collection.mapReduce(map, reduce, {out : {replace: 'mapreduce_integration_test'}, verbose:true});
                test.ok(result.stats != null);
                db.close();
              });
              // Mapreduce using a provided scope containing a javascript function executed 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');
              
                // Create a test collection
                var collection = db.collection('test_map_reduce_functions_scope_with_generators');
              
                // Insert some test documents
                yield collection.insertMany([{'user_id':1, 'timestamp':new Date()}
                  , {'user_id':2, 'timestamp':new Date()}], {w:1});
              
                // Map function
                var map = function(){
                    emit(fn(this.timestamp.getYear()), 1);
                }
              
                // Reduce function
                var reduce = function(k, v){
                    count = 0;
                    for(i = 0; i < v.length; i++) {
                        count += v[i];
                    }
                    return count;
                }
              
                // Javascript function available in the map reduce scope
                var t = function(val){ return val+1; }
              
                // Execute the map reduce with the custom scope
                var o = {};
                o.scope =  { fn: new Code(t.toString()) }
                o.out = { replace: 'replacethiscollection' }
              
                // Execute with output collection
                var outCollection = yield collection.mapReduce(map, reduce, o);
                // Find all entries in the map-reduce collection
                var results = yield outCollection.find().toArray()
                test.equal(2, results[0].value);
              
                // mapReduce with scope containing plain function
                var o = {};
                o.scope =  { fn: t }
                o.out = { replace: 'replacethiscollection' }
              
                // Execute with outCollection
                var outCollection = yield collection.mapReduce(map, reduce, o);
                // Find all entries in the map-reduce collection
                var results = yield outCollection.find().toArray();
                test.equal(2, results[0].value)
              
                db.close();
              });
              // Mapreduce using a scope containing javascript objects with functions 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');
              
                // Create a test collection
                var collection = db.collection('test_map_reduce_functions_scope_objects_with_generators');
              
                // Insert some test documents
                yield collection.insertMany([{'user_id':1, 'timestamp':new Date()}
                  , {'user_id':2, 'timestamp':new Date()}], {w:1});
              
                // Map function
                var map = function(){
                  emit(obj.fn(this.timestamp.getYear()), 1);
                }
              
                // Reduce function
                var reduce = function(k, v){
                  count = 0;
                  for(i = 0; i < v.length; i++) {
                    count += v[i];
                  }
                  return count;
                }
              
                // Javascript function available in the map reduce scope
                var t = function(val){ return val+1; }
              
                // Execute the map reduce with the custom scope containing objects
                var o = {};
                o.scope =  { obj: {fn: new Code(t.toString())} }
                o.out = { replace: 'replacethiscollection' }
              
                // Execute returning outCollection
                var outCollection = yield collection.mapReduce(map, reduce, o);
              
                // Find all entries in the map-reduce collection
                var results = yield outCollection.find().toArray();
                test.equal(2, results[0].value)
              
                // mapReduce with scope containing plain function
                var o = {};
                o.scope =  { obj: {fn: t} }
                o.out = { replace: 'replacethiscollection' }
              
                // Execute returning outCollection
                var outCollection = yield collection.mapReduce(map, reduce, o);
                // Find all entries in the map-reduce collection
                var results = yield outCollection.find().toArray();
                test.equal(2, results[0].value)
                db.close();
              });

              options(callback){Promise}

              Returns the options of the collection.

              Name Type Description
              callback Collection~resultCallback optional

              The results callback

              Returns:
              Promise if no callback passed
              Examples
              // An example returning the options for a collection.
              
              var MongoClient = require('mongodb').MongoClient,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
              
                // Create a test collection that we are getting the options back from
                db.createCollection('test_collection_options', {'capped':true, 'size':1024}, function(err, collection) {
                  test.equal('test_collection_options', collection.collectionName);
              
                  // Let's fetch the collection options
                  collection.options(function(err, options) {
                    test.equal(true, options.capped);
                    test.ok(options.size >= 1024);
              
                    db.close();
                  });
                });
              });
              // An example returning the options for a collection using a Promise.
              
              var MongoClient = require('mongodb').MongoClient,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
              
                // Create a test collection that we are getting the options back from
                db.createCollection('test_collection_options_with_promise', {'capped':true, 'size':1024}).then(function(collection) {
                  test.equal('test_collection_options_with_promise', collection.collectionName);
              
                  // Let's fetch the collection options
                  collection.options().then(function(options) {
                    test.equal(true, options.capped);
                    test.ok(options.size >= 1024);
              
                    db.close();
                  });
                });
              });
              // An example returning the options for a collection 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');
              
                // Create a test collection that we are getting the options back from
                var collection = yield db.createCollection('test_collection_options_with_generators', {'capped':true, 'size':1024});
                test.equal('test_collection_options_with_generators', collection.collectionName);
              
                // Let's fetch the collection options
                var options = yield collection.options();
                test.equal(true, options.capped);
                test.ok(options.size >= 1024);
              
                db.close();
              });

              parallelCollectionScan(options, callback){Promise}

              Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are
              no ordering guarantees for returned results.

              Name Type Default Description
              options object null optional

              Optional settings.

              Name Type Default Description
              readPreference ReadPreference | string null optional

              The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).

              batchSize number null optional

              Set the batchSize for the getMoreCommand when iterating over the query results.

              numCursors number 1 optional

              The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors)

              raw boolean false optional

              Return all BSON documents as Raw Buffer documents.

              callback Collection~parallelCollectionScanCallback optional

              The command result callback

              Returns:
              Promise if no callback passed
              Examples
              // A parallelCollectionScan example
              
              var MongoClient = require('mongodb').MongoClient,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                var docs = [];
              
                // Insert some documents
                for(var i = 0; i < 1000; i++) {
                  docs.push({a:i});
                }
              
                // Get the collection
                var collection = db.collection('parallelCollectionScan');
                // Insert 1000 documents in a batch
                collection.insertMany(docs, function(err, result) {
                  var results = [];
                  var numCursors = 3;
              
                  // Execute parallelCollectionScan command
                  collection.parallelCollectionScan({numCursors:numCursors}, function(err, cursors) {
                    test.equal(null, err);
                    test.ok(cursors != null);
                    test.ok(cursors.length > 0);
                    var left = cursors.length;
              
                    for(var i = 0; i < cursors.length; i++) {
                      cursors[i].toArray(function(err, items) {
                        test.equal(err, null);
              
                        // Add docs to results array
                        results = results.concat(items);
                        left = left - 1;
              
                        // No more cursors let's ensure we got all results
                        if(left == 0) {
                          test.equal(docs.length, results.length);
              
                          db.close();
                        }
                      });
                    }
                  });
                });
              });
              // A parallelCollectionScan example using a Promise.
              
              var MongoClient = require('mongodb').MongoClient,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                var docs = [];
              
                // Insert some documents
                for(var i = 0; i < 1000; i++) {
                  docs.push({a:i});
                }
              
                // Get the collection
                var collection = db.collection('parallelCollectionScan_with_promise');
                // Insert 1000 documents in a batch
                collection.insertMany(docs).then(function(result) {
                  var results = [];
                  var numCursors = 3;
              
                  // Execute parallelCollectionScan command
                  collection.parallelCollectionScan({numCursors:numCursors}).then(function(cursors) {
                    test.ok(cursors != null);
                    test.ok(cursors.length > 0);
                    var left = cursors.length;
              
                    for(var i = 0; i < cursors.length; i++) {
                      cursors[i].toArray().then(function(items) {
                        // Add docs to results array
                        results = results.concat(items);
                        left = left - 1;
              
                        // No more cursors let's ensure we got all results
                        if(left == 0) {
                          test.equal(docs.length, results.length);
              
                          db.close();
                        }
                      });
                    }
                  });
                });
              });
              // A parallelCollectionScan example 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');
                var docs = [];
              
                // Insert some documents
                for(var i = 0; i < 1000; i++) {
                  docs.push({a:i});
                }
              
                // Get the collection
                var collection = db.collection('parallelCollectionScan_with_generators');
                // Insert 1000 documents in a batch
                yield collection.insertMany(docs);
                var results = [];
                var numCursors = 3;
              
                // Execute parallelCollectionScan command
                var cursors = yield collection.parallelCollectionScan({numCursors:numCursors});
                test.ok(cursors != null);
                test.ok(cursors.length >= 0);
              
                for(var i = 0; i < cursors.length; i++) {
                  var items = yield cursors[i].toArray();
                  // Add docs to results array
                  results = results.concat(items);
                }
              
                test.equal(docs.length, results.length);
                db.close();
              });

              reIndex(callback){Promise}

              Reindex all indexes on the collection
              Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections.

              Name Type Description
              callback Collection~resultCallback optional

              The command result callback

              Returns:
              Promise if no callback passed
              Examples
              // An example showing how to force a reindex of a collection.
              
              var MongoClient = require('mongodb').MongoClient,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
              
                // Create a collection we want to drop later
                var collection = db.collection('shouldCorrectlyForceReindexOnCollection');
                // Insert a bunch of documents for the index
                collection.insertMany([{a:1, b:1}
                  , {a:2, b:2}, {a:3, b:3}, {a:4, b:4, c:4}], {w:1}, function(err, result) {
                  test.equal(null, err);
              
                  // Create an index on the a field
                  collection.ensureIndex({a:1, b:1}
                    , {unique:true, background:true, w:1}, function(err, indexName) {
              
                    // Force a reindex of the collection
                    collection.reIndex(function(err, result) {
                      test.equal(null, err);
                      test.equal(true, result);
              
                      // Verify that the index is gone
                      collection.indexInformation(function(err, indexInformation) {
                        test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_);
                        test.deepEqual([ [ 'a', 1 ], [ 'b', 1 ] ], indexInformation.a_1_b_1);
              
                        db.close();
                      });
                    });
                  });
                });
              });
              // An example showing how to force a reindex of a collection using a Promise.
              
              var MongoClient = require('mongodb').MongoClient,
                test = require('assert');
              MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
              
                // Create a collection we want to drop later
                var collection = db.collection('shouldCorrectlyForceReindexOnCollection_with_promise');
                // Insert a bunch of documents for the index
                collection.insertMany([{a:1, b:1}
                  , {a:2, b:2}, {a:3, b:3}, {a:4, b:4, c:4}], {w:1}).then(function(result) {
              
                  // Create an index on the a field
                  collection.ensureIndex({a:1, b:1}
                    , {unique:true, background:true, w:1}).then(function(indexName) {
              
                    // Force a reindex of the collection
                    collection.reIndex().then(function(result) {
                      test.equal(true, result);
              
                      // Verify that the index is gone
                      collection.indexInformation().then(function(indexInformation) {
                        test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_);
                        test.deepEqual([ [ 'a', 1 ], [ 'b', 1 ] ], indexInformation.a_1_b_1);
              
                        db.close();
                      });
                    });
                  });
                });
              });
              // An example showing how to force a reindex of a collection 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');
              
                // Create a collection we want to drop later
                var collection = db.collection('shouldCorrectlyForceReindexOnCollection_with_generators');
                // Insert a bunch of documents for the index
                yield collection.insertMany([{a:1, b:1}
                  , {a:2, b:2}, {a:3, b:3}, {a:4, b:4, c:4}], {w:1});
              
                // Create an index on the a field
                yield collection.ensureIndex({a:1, b:1}
                  , {unique:true, background:true, w:1});
              
                // Force a reindex of the collection
                var result = yield collection.reIndex();
                test.equal(true, result);
              
                // Verify that the index is gone
                var indexInformation = yield collection.indexInformation();
                test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_);
                test.deepEqual([ [ 'a', 1 ], [ 'b', 1 ] ], indexInformation.a_1_b_1);
              
                db.close();
              });

              remove(selector, options, callback){Promise}

              Remove documents.

              Name Type Default Description
              selector object

              The selector for the update operation.

              options object null optional

              Optional settings.

              Name Type Default Description
              w number | string null optional

              The write concern.

              wtimeout number null optional

              The write concern timeout.

              j boolean false optional

              Specify a journal write concern.

              single boolean false optional

              Removes the first document found.

              callback Collection~writeOpCallback optional

              The command result callback

              Deprecated
              • use deleteOne, deleteMany or bulkWrite
                Returns:
                Promise if no callback passed
                Examples
                // An example removing all documents in a collection not using safe mode
                
                var MongoClient = require('mongodb').MongoClient,
                  test = require('assert');
                MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                
                  // Fetch a collection to insert document into
                  var collection = db.collection("remove_all_documents_no_safe");
                  // Insert a bunch of documents
                  collection.insertMany([{a:1}, {b:2}], {w:1}, function(err, result) {
                    test.equal(null, err);
                
                    // Remove all the document
                    collection.removeMany();
                
                    // Fetch all results
                    collection.find().toArray(function(err, items) {
                      test.equal(null, err);
                      test.equal(0, items.length);
                      db.close();
                    });
                  })
                });
                // An example removing a subset of documents using safe mode to ensure removal of documents
                
                var MongoClient = require('mongodb').MongoClient,
                  test = require('assert');
                MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                  test.equal(null, err);
                
                  // Fetch a collection to insert document into
                  var collection = db.collection("remove_subset_of_documents_safe");
                  // Insert a bunch of documents
                  collection.insertMany([{a:1}, {b:2}], {w:1}, function(err, result) {
                    test.equal(null, err);
                
                    // Remove all the document
                    collection.removeOne({a:1}, {w:1}, function(err, r) {
                      test.equal(null, err);
                      test.equal(1, r.result.n);
                      db.close();
                    });
                  });
                });
                // An example removing all documents in a collection not using safe mode using a Promise.
                
                var MongoClient = require('mongodb').MongoClient,
                  test = require('assert');
                MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                
                  // Fetch a collection to insert document into
                  var collection = db.collection("remove_all_documents_no_safe_with_promise");
                  // Insert a bunch of documents
                  collection.insertMany([{a:1}, {b:2}], {w:1}).then(function(result) {
                    // Remove all the document
                    collection.removeMany();
                
                    // Fetch all results
                    collection.find().toArray().then(function(items) {
                      test.equal(0, items.length);
                      db.close();
                    });
                  })
                });
                // An example removing a subset of documents using safe mode to ensure removal of documents using a Promise.
                
                var MongoClient = require('mongodb').MongoClient,
                  test = require('assert');
                MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                
                  // Fetch a collection to insert document into
                  var collection = db.collection("remove_subset_of_documents_safe_with_promise");
                  // Insert a bunch of documents
                  collection.insertMany([{a:1}, {b:2}], {w:1}).then(function(result) {
                    // Remove all the document
                    collection.removeOne({a:1}, {w:1}).then(function(r) {
                      test.equal(1, r.result.n);
                      db.close();
                    });
                  });
                });
                // An example removing all documents in a collection not using safe mode 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');
                
                  // Fetch a collection to insert document into
                  var collection = db.collection("remove_all_documents_no_safe_with_generators");
                
                  // Insert a bunch of documents
                  yield collection.insertMany([{a:1}, {b:2}], {w:1});
                
                  // Remove all the document
                  collection.removeMany();
                
                  // Fetch all results
                  var items = yield collection.find().toArray();
                  test.equal(0, items.length);
                  db.close();
                });
                // An example removing a subset of documents using safe mode to ensure removal of documents 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');
                
                  // Fetch a collection to insert document into
                  var collection = db.collection("remove_subset_of_documents_safe_with_generators");
                  // Insert a bunch of documents
                  yield collection.insertMany([{a:1}, {b:2}], {w:1});
                  // Remove all the document
                  var r = yield collection.removeOne({a:1}, {w:1});
                  test.equal(1, r.result.n);
                  db.close();
                });

                rename(newName, options, callback){Promise}

                Rename the collection.

                Name Type Default Description
                newName string

                New name of of the collection.

                options object null optional

                Optional settings.

                Name Type Default Description
                dropTarget boolean false optional

                Drop the target name collection if it previously exists.

                callback Collection~collectionResultCallback optional

                The results callback

                Returns:
                Promise if no callback passed
                Examples
                // An example of illegal and legal renaming of a collection
                
                var MongoClient = require('mongodb').MongoClient,
                  test = require('assert');
                MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                  // Open a couple of collections
                  db.createCollection('test_rename_collection', function(err, collection1) {
                    db.createCollection('test_rename_collection2', function(err, collection2) {
                      // Attemp to rename a collection to a number
                      try {
                        collection1.rename(5, function(err, collection) {});
                      } catch(err) {
                        test.ok(err instanceof Error);
                        test.equal("collection name must be a String", err.message);
                      }
                
                      // Attemp to rename a collection to an empty string
                      try {
                        collection1.rename("", function(err, collection) {});
                      } catch(err) {
                        test.ok(err instanceof Error);
                        test.equal("collection names cannot be empty", err.message);
                      }
                
                      // Attemp to rename a collection to an illegal name including the character $
                      try {
                        collection1.rename("te$t", function(err, collection) {});
                      } catch(err) {
                        test.ok(err instanceof Error);
                        test.equal("collection names must not contain '$'", err.message);
                      }
                
                      // Attemp to rename a collection to an illegal name starting with the character .
                      try {
                        collection1.rename(".test", function(err, collection) {});
                      } catch(err) {
                        test.ok(err instanceof Error);
                        test.equal("collection names must not start or end with '.'", err.message);
                      }
                
                      // Attemp to rename a collection to an illegal name ending with the character .
                      try {
                        collection1.rename("test.", function(err, collection) {});
                      } catch(err) {
                        test.ok(err instanceof Error);
                        test.equal("collection names must not start or end with '.'", err.message);
                      }
                
                      // Attemp to rename a collection to an illegal name with an empty middle name
                      try {
                        collection1.rename("tes..t", function(err, collection) {});
                      } catch(err) {
                        test.equal("collection names cannot be empty", err.message);
                      }
                
                      // Insert a couple of documents
                      collection1.insertMany([{'x':1}, {'x':2}], {w:1}, function(err, docs) {
                
                        // Attemp to rename the first collection to the second one, this will fail
                        collection1.rename('test_rename_collection2', function(err, collection) {
                          test.ok(err instanceof Error);
                          test.ok(err.message.length > 0);
                
                          // Attemp to rename the first collection to a name that does not exist
                          // this will be succesful
                          collection1.rename('test_rename_collection3', function(err, collection2) {
                            test.equal("test_rename_collection3", collection2.collectionName);
                
                            // Ensure that the collection is pointing to the new one
                            collection2.count(function(err, count) {
                              test.equal(2, count);
                              db.close();
                            });
                          });
                        });
                      });
                
                    });
                  });
                });
                // An example of illegal and legal renaming of a collection using a Promise.
                
                var MongoClient = require('mongodb').MongoClient,
                  test = require('assert');
                MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                  // Open a couple of collections
                  db.createCollection('test_rename_collection_with_promise').then(function(collection1) {
                    db.createCollection('test_rename_collection2_with_promise').then(function(collection2) {
                      // Attemp to rename a collection to a number
                      try {
                        collection1.rename(5, function(err, collection) {});
                      } catch(err) {
                        test.ok(err instanceof Error);
                        test.equal("collection name must be a String", err.message);
                      }
                
                      // Attemp to rename a collection to an empty string
                      try {
                        collection1.rename("", function(err, collection) {});
                      } catch(err) {
                        test.ok(err instanceof Error);
                        test.equal("collection names cannot be empty", err.message);
                      }
                
                      // Attemp to rename a collection to an illegal name including the character $
                      try {
                        collection1.rename("te$t", function(err, collection) {});
                      } catch(err) {
                        test.ok(err instanceof Error);
                        test.equal("collection names must not contain '$'", err.message);
                      }
                
                      // Attemp to rename a collection to an illegal name starting with the character .
                      try {
                        collection1.rename(".test", function(err, collection) {});
                      } catch(err) {
                        test.ok(err instanceof Error);
                        test.equal("collection names must not start or end with '.'", err.message);
                      }
                
                      // Attemp to rename a collection to an illegal name ending with the character .
                      try {
                        collection1.rename("test.", function(err, collection) {});
                      } catch(err) {
                        test.ok(err instanceof Error);
                        test.equal("collection names must not start or end with '.'", err.message);
                      }
                
                      // Attemp to rename a collection to an illegal name with an empty middle name
                      try {
                        collection1.rename("tes..t", function(err, collection) {});
                      } catch(err) {
                        test.equal("collection names cannot be empty", err.message);
                      }
                
                      // Insert a couple of documents
                      collection1.insertMany([{'x':1}, {'x':2}], {w:1}).then(function(docs) {
                
                        // Attemp to rename the first collection to the second one, this will fail
                        collection1.rename('test_rename_collection2_with_promise').then(function(err, collection) {
                        }).catch(function(err) {
                          test.ok(err instanceof Error);
                          test.ok(err.message.length > 0);
                
                          // Attemp to rename the first collection to a name that does not exist
                          // this will be succesful
                          collection1.rename('test_rename_collection3_with_promise').then(function(collection2) {
                            test.equal("test_rename_collection3_with_promise", collection2.collectionName);
                
                            // Ensure that the collection is pointing to the new one
                            collection2.count().then(function(count) {
                              test.equal(2, count);
                              db.close();
                            });
                          });
                        });
                      });
                
                    });
                  });
                });
                // An example of illegal and legal renaming of a collection 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');
                  // Open a couple of collections
                  var collection1 = yield db.createCollection('test_rename_collection_with_generators');
                  var collection2 = yield db.createCollection('test_rename_collection2_with_generators');
                  // Attemp to rename a collection to a number
                  try {
                    collection1.rename(5, function(err, collection) {});
                  } catch(err) {
                    test.ok(err instanceof Error);
                    test.equal("collection name must be a String", err.message);
                  }
                
                  // Attemp to rename a collection to an empty string
                  try {
                    collection1.rename("", function(err, collection) {});
                  } catch(err) {
                    test.ok(err instanceof Error);
                    test.equal("collection names cannot be empty", err.message);
                  }
                
                  // Attemp to rename a collection to an illegal name including the character $
                  try {
                    collection1.rename("te$t", function(err, collection) {});
                  } catch(err) {
                    test.ok(err instanceof Error);
                    test.equal("collection names must not contain '$'", err.message);
                  }
                
                  // Attemp to rename a collection to an illegal name starting with the character .
                  try {
                    collection1.rename(".test", function(err, collection) {});
                  } catch(err) {
                    test.ok(err instanceof Error);
                    test.equal("collection names must not start or end with '.'", err.message);
                  }
                
                  // Attemp to rename a collection to an illegal name ending with the character .
                  try {
                    collection1.rename("test.", function(err, collection) {});
                  } catch(err) {
                    test.ok(err instanceof Error);
                    test.equal("collection names must not start or end with '.'", err.message);
                  }
                
                  // Attemp to rename a collection to an illegal name with an empty middle name
                  try {
                    collection1.rename("tes..t", function(err, collection) {});
                  } catch(err) {
                    test.equal("collection names cannot be empty", err.message);
                  }
                
                  // Insert a couple of documents
                  yield collection1.insertMany([{'x':1}, {'x':2}], {w:1});
                
                  try {
                    // Attemp to rename the first collection to the second one, this will fail
                    yield collection1.rename('test_rename_collection2_with_generators');
                  } catch(err) {
                    test.ok(err instanceof Error);
                    test.ok(err.message.length > 0);
                
                    // Attemp to rename the first collection to a name that does not exist
                    // this will be succesful
                    var collection2 = yield collection1.rename('test_rename_collection3_with_generators');
                    test.equal("test_rename_collection3_with_generators", collection2.collectionName);
                
                    // Ensure that the collection is pointing to the new one
                    var count = yield collection2.count();
                    test.equal(2, count);
                    db.close();
                  }
                });

                replaceOne(filter, doc, options, callback){Promise}

                Replace a document on MongoDB

                Name Type Default Description
                filter object

                The Filter used to select the document to update

                doc object

                The Document that replaces the matching document

                options object null optional

                Optional settings.

                Name Type Default Description
                upsert boolean false optional

                Update operation is an upsert.

                w number | string null optional

                The write concern.

                wtimeout number null optional

                The write concern timeout.

                j boolean false optional

                Specify a journal write concern.

                bypassDocumentValidation boolean false optional

                Allow driver to bypass schema validation in MongoDB 3.2 or higher.

                callback Collection~updateWriteOpCallback optional

                The command result callback

                Returns:
                Promise if no callback passed

                save(doc, options, callback){Promise}

                Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic
                operators and update instead for more efficient operations.

                Name Type Default Description
                doc object

                Document to save

                options object null optional

                Optional settings.

                Name Type Default Description
                w number | string null optional

                The write concern.

                wtimeout number null optional

                The write concern timeout.

                j boolean false optional

                Specify a journal write concern.

                callback Collection~writeOpCallback optional

                The command result callback

                Deprecated
                • use insertOne, insertMany, updateOne or updateMany
                  Returns:
                  Promise if no callback passed
                  Examples
                  // Example of a simple document save with safe set to false
                  
                  var MongoClient = require('mongodb').MongoClient,
                    test = require('assert');
                  MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                  
                    // Fetch the collection
                    var collection = db.collection("save_a_simple_document");
                    // Save a document with no safe option
                    collection.save({hello:'world'});
                  
                    // Wait for a second
                    setTimeout(function() {
                  
                      // Find the saved document
                      collection.findOne({hello:'world'}, function(err, item) {
                        test.equal(null, err);
                        test.equal('world', item.hello);
                        db.close();
                      });
                    }, 2000);
                  });
                  // Example of a simple document save and then resave with safe set to true
                  
                  var MongoClient = require('mongodb').MongoClient,
                    test = require('assert');
                  MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                  
                    // Fetch the collection
                    var collection = db.collection("save_a_simple_document_modify_it_and_resave_it");
                  
                    // Save a document with no safe option
                    collection.save({hello:'world'}, {w:1}, function(err, result) {
                  
                      // Find the saved document
                      collection.findOne({hello:'world'}, function(err, item) {
                        test.equal(null, err);
                        test.equal('world', item.hello);
                  
                        // Update the document
                        item['hello2'] = 'world2';
                  
                        // Save the item with the additional field
                        collection.save(item, {w:1}, function(err, result) {
                  
                          // Find the changed document
                          collection.findOne({hello:'world'}, function(err, item) {
                            test.equal(null, err);
                            test.equal('world', item.hello);
                            test.equal('world2', item.hello2);
                  
                            db.close();
                          });
                        });
                      });
                    });
                  });
                  // Example of a simple document save with safe set to false using a Promise.
                  
                  var MongoClient = require('mongodb').MongoClient,
                    test = require('assert');
                  MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                  
                    // Fetch the collection
                    var collection = db.collection("save_a_simple_document_with_promise");
                    // Save a document with no safe option
                    collection.save({hello:'world'});
                  
                    // Wait for a second
                    setTimeout(function() {
                  
                      // Find the saved document
                      collection.findOne({hello:'world'}).then(function(item) {
                        test.equal('world', item.hello);
                        db.close();
                      });
                    }, 2000);
                  });
                  // Example of a simple document save and then resave with safe set to true using a Promise.
                  
                  var MongoClient = require('mongodb').MongoClient,
                    test = require('assert');
                  MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                  
                    // Fetch the collection
                    var collection = db.collection("save_a_simple_document_modify_it_and_resave_it_with_promise");
                  
                    // Save a document with no safe option
                    collection.save({hello:'world'}, {w:1}).then(function(result) {
                  
                      // Find the saved document
                      collection.findOne({hello:'world'}).then(function(item) {
                        test.equal('world', item.hello);
                  
                        // Update the document
                        item['hello2'] = 'world2';
                  
                        // Save the item with the additional field
                        collection.save(item, {w:1}).then(function(result) {
                  
                          // Find the changed document
                          collection.findOne({hello:'world'}).then(function(item) {
                            test.equal('world', item.hello);
                            test.equal('world2', item.hello2);
                  
                            db.close();
                          });
                        });
                      });
                    });
                  });
                  // Example of a simple document save with safe set to false 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');
                  
                    // Fetch the collection
                    var collection = db.collection("save_a_simple_document_with_generators");
                    // Save a document with no safe option
                    collection.save({hello:'world'});
                  
                    // Wait for a second
                    setTimeout(function() {
                      co(function*() {
                        // Find the saved document
                        var item = yield collection.findOne({hello:'world'});
                        test.equal('world', item.hello);
                        db.close();
                      });
                    }, 2000);
                  });
                  // Example of a simple document save and then resave with safe set to true 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');
                  
                    // Fetch the collection
                    var collection = db.collection("save_a_simple_document_modify_it_and_resave_it_with_generators");
                  
                    // Save a document with no safe option
                    yield collection.save({hello:'world'}, {w:1});
                  
                    // Find the saved document
                    var item = yield collection.findOne({hello:'world'})
                    test.equal('world', item.hello);
                  
                    // Update the document
                    item['hello2'] = 'world2';
                  
                    // Save the item with the additional field
                    yield collection.save(item, {w:1});
                  
                    // Find the changed document
                    var item = yield collection.findOne({hello:'world'});
                    test.equal('world', item.hello);
                    test.equal('world2', item.hello2);
                  
                    db.close();
                  });

                  stats(options, callback){Promise}

                  Get all the collection statistics.

                  Name Type Default Description
                  options object null optional

                  Optional settings.

                  Name Type Default Description
                  scale number null optional

                  Divide the returned sizes by scale value.

                  callback Collection~resultCallback optional

                  The collection result callback

                  Returns:
                  Promise if no callback passed
                  Examples
                  // Example of retrieving a collections stats
                  
                  var MongoClient = require('mongodb').MongoClient,
                    test = require('assert');
                  MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                  
                    // Crete the collection for the distinct example
                    var collection = db.collection('collection_stats_test');
                  
                    // Insert some documents
                    collection.insertMany([{a:1}, {hello:'world'}], {w:1}, function(err, result) {
                  
                      // Retrieve the statistics for the collection
                      collection.stats(function(err, stats) {
                        test.equal(2, stats.count);
                  
                        db.close();
                      });
                    });
                  });
                  // Example of retrieving a collections stats using a Promise.
                  
                  var MongoClient = require('mongodb').MongoClient,
                    test = require('assert');
                  MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                  
                    // Crete the collection for the distinct example
                    var collection = db.collection('collection_stats_test_with_promise');
                  
                    // Insert some documents
                    collection.insertMany([{a:1}, {hello:'world'}], {w:1}).then(function(result) {
                  
                      // Retrieve the statistics for the collection
                      collection.stats().then(function(stats) {
                        test.equal(2, stats.count);
                  
                        db.close();
                      });
                    });
                  });
                  // Example of retrieving a collections stats 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');
                  
                    // Crete the collection for the distinct example
                    var collection = db.collection('collection_stats_test_with_generators');
                  
                    // Insert some documents
                    yield collection.insertMany([{a:1}, {hello:'world'}], {w:1});
                  
                    // Retrieve the statistics for the collection
                    var stats = yield collection.stats();
                    test.equal(2, stats.count);
                  
                    db.close();
                  });

                  update(selector, document, options, callback){Promise}

                  Updates documents.

                  Name Type Default Description
                  selector object

                  The selector for the update operation.

                  document object

                  The update document.

                  options object null optional

                  Optional settings.

                  Name Type Default Description
                  w number | string null optional

                  The write concern.

                  wtimeout number null optional

                  The write concern timeout.

                  j boolean false optional

                  Specify a journal write concern.

                  upsert boolean false optional

                  Update operation is an upsert.

                  multi boolean false optional

                  Update one/all documents with operation.

                  bypassDocumentValidation boolean false optional

                  Allow driver to bypass schema validation in MongoDB 3.2 or higher.

                  collation object null optional

                  Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).

                  callback Collection~writeOpCallback optional

                  The command result callback

                  Deprecated
                  • use updateOne, updateMany or bulkWrite
                    Throws:
                    Returns:
                    Promise if no callback passed
                    Examples
                    // Example of a simple document update with safe set to false on an existing document using a Promise.
                    
                    var MongoClient = require('mongodb').MongoClient,
                      test = require('assert');
                    MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                    
                      // Get a collection
                      var collection = db.collection('update_a_simple_document_with_promise');
                    
                      // Insert a document, then update it
                      collection.insertOne({a:1}, {w:1}).then(function(doc) {
                    
                        // Update the document with an atomic operator
                        collection.updateOne({a:1}, {$set:{b:2}});
                    
                        // Wait for a second then fetch the document
                        setTimeout(function() {
                    
                          // Fetch the document that we modified
                          collection.findOne({a:1}).then(function(item) {
                            test.equal(1, item.a);
                            test.equal(2, item.b);
                            db.close();
                          });
                        }, 1000);
                      });
                    });
                    // Example of a simple document update using upsert (the document will be inserted if it does not exist) using a Promise.
                    
                    var MongoClient = require('mongodb').MongoClient,
                      test = require('assert');
                    MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                    
                      // Get a collection
                      var collection = db.collection('update_a_simple_document_upsert_with_promise');
                      // Update the document using an upsert operation, ensuring creation if it does not exist
                      collection.updateOne({a:1}, {b:2, a:1}, {upsert:true, w: 1}).then(function(result) {
                        test.equal(1, result.result.n);
                    
                        // Fetch the document that we modified and check if it got inserted correctly
                        collection.findOne({a:1}).then(function(item) {
                          test.equal(1, item.a);
                          test.equal(2, item.b);
                          db.close();
                        });
                      });
                    });
                    // Example of an update across multiple documents using the multi option and using a Promise.
                    
                    var MongoClient = require('mongodb').MongoClient,
                      test = require('assert');
                    MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                    
                      // Get a collection
                      var collection = db.collection('update_a_simple_document_multi_with_promise');
                    
                      // Insert a couple of documentations
                      collection.insertMany([{a:1, b:1}, {a:1, b:2}], {w:1}).then(function(result) {
                    
                        var o = {w:1};
                        collection.updateMany({a:1}, {$set:{b:0}}, o).then(function(r) {
                          test.equal(2, r.result.n);
                    
                          // Fetch all the documents and verify that we have changed the b value
                          collection.find().toArray().then(function(items) {
                            test.equal(1, items[0].a);
                            test.equal(0, items[0].b);
                            test.equal(1, items[1].a);
                            test.equal(0, items[1].b);
                    
                            db.close();
                          });
                        })
                      });
                    });
                    // Example of a simple document update with safe set to false on an existing document 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');
                    
                      // Get a collection
                      var collection = db.collection('update_a_simple_document_with_generators');
                    
                      // Insert a document, then update it
                      yield collection.insertOne({a:1}, {w:1});
                    
                      // Update the document with an atomic operator
                      collection.updateOne({a:1}, {$set:{b:2}});
                    
                      // Wait for a second then fetch the document
                      setTimeout(function() {
                        co(function*() {
                          // Fetch the document that we modified
                          var item = yield collection.findOne({a:1});
                          test.equal(1, item.a);
                          test.equal(2, item.b);
                    
                          db.close();
                        });
                      }, 1000);
                    });
                    // Example of a simple document update using upsert (the document will be inserted if it does not exist) 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');
                    
                      // Get a collection
                      var collection = db.collection('update_a_simple_document_upsert_with_generators');
                      // Update the document using an upsert operation, ensuring creation if it does not exist
                      var result = yield collection.updateOne({a:1}, {b:2, a:1}, {upsert:true, w: 1});
                      test.equal(1, result.result.n);
                    
                      // Fetch the document that we modified and check if it got inserted correctly
                      var item = yield collection.findOne({a:1});
                      test.equal(1, item.a);
                      test.equal(2, item.b);
                      db.close();
                    });
                    // Example of an update across multiple documents using the multi option and 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');
                    
                      // Get a collection
                      var collection = db.collection('update_a_simple_document_multi_with_generators');
                    
                      // Insert a couple of documentations
                      yield collection.insertMany([{a:1, b:1}, {a:1, b:2}], {w:1});
                    
                      var o = {w:1};
                      var r = yield collection.updateMany({a:1}, {$set:{b:0}}, o);
                      test.equal(2, r.result.n);
                    
                      // Fetch all the documents and verify that we have changed the b value
                      var items = yield collection.find().toArray();
                      test.equal(1, items[0].a);
                      test.equal(0, items[0].b);
                      test.equal(1, items[1].a);
                      test.equal(0, items[1].b);
                    
                      db.close();
                    });

                    updateMany(filter, update, options, callback){Promise}

                    Update multiple documents on MongoDB

                    Name Type Default Description
                    filter object

                    The Filter used to select the document to update

                    update object

                    The update operations to be applied to the document

                    options object null optional

                    Optional settings.

                    Name Type Default Description
                    upsert boolean false optional

                    Update operation is an upsert.

                    w number | string null optional

                    The write concern.

                    wtimeout number null optional

                    The write concern timeout.

                    j boolean false optional

                    Specify a journal write concern.

                    callback Collection~updateWriteOpCallback optional

                    The command result callback

                    Returns:
                    Promise if no callback passed
                    Examples
                    // Example of an update across multiple documents using the multi option.
                    
                    var MongoClient = require('mongodb').MongoClient,
                      test = require('assert');
                    MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                    
                      // Get a collection
                      var collection = db.collection('update_a_simple_document_multi');
                    
                      // Insert a couple of documentations
                      collection.insertMany([{a:1, b:1}, {a:1, b:2}], {w:1}, function(err, result) {
                    
                        var o = {w:1};
                        collection.updateMany({a:1}, {$set:{b:0}}, o, function(err, r) {
                          test.equal(null, err);
                          test.equal(2, r.result.n);
                    
                          // Fetch all the documents and verify that we have changed the b value
                          collection.find().toArray(function(err, items) {
                            test.equal(null, err);
                            test.equal(1, items[0].a);
                            test.equal(0, items[0].b);
                            test.equal(1, items[1].a);
                            test.equal(0, items[1].b);
                    
                            db.close();
                          });
                        })
                      });
                    });
                    // Example of a simple updateMany operation
                    
                    var MongoClient = require('mongodb').MongoClient,
                      test = require('assert');
                    MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                      // Get the collection
                      var col = db.collection('update_many');
                      col.insertMany([{a:1}, {a:1}], function(err, r) {
                        test.equal(null, err);
                        test.equal(2, r.insertedCount);
                    
                        // Update all documents
                        col.updateMany({a:1}, {$set: {b: 1}}, function(err, r) {
                          test.equal(null, err);
                          test.equal(2, r.matchedCount);
                          test.equal(2, r.modifiedCount);
                    
                          // Finish up test
                          db.close();
                        });
                      });
                    });
                    // Example of a simple updateMany operation using a Promise.
                    
                    var MongoClient = require('mongodb').MongoClient,
                      test = require('assert');
                    MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                      // Get the collection
                      var col = db.collection('update_many_with_promise');
                      col.insertMany([{a:1}, {a:1}]).then(function(r) {
                        test.equal(2, r.insertedCount);
                    
                        // Update all documents
                        col.updateMany({a:1}, {$set: {b: 1}}).then(function(r) {
                          if(r.n) {
                            test.equal(2, r.n);
                          } else {
                            test.equal(2, r.matchedCount);
                            test.equal(2, r.modifiedCount);
                          }
                    
                          // Finish up test
                          db.close();
                        });
                      });
                    });
                    // Example of a simple updateMany operation 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');
                      // Get the collection
                      var col = db.collection('update_many_with_generators');
                      var r = yield col.insertMany([{a:1}, {a:1}]);
                      test.equal(2, r.insertedCount);
                    
                      // Update all documents
                      var r = yield col.updateMany({a:1}, {$set: {b: 1}});
                      test.equal(2, r.matchedCount);
                      test.equal(2, r.modifiedCount);
                    
                      // Finish up test
                      db.close();
                    });

                    updateOne(filter, update, options, callback){Promise}

                    Update a single document on MongoDB

                    Name Type Default Description
                    filter object

                    The Filter used to select the document to update

                    update object

                    The update operations to be applied to the document

                    options object null optional

                    Optional settings.

                    Name Type Default Description
                    upsert boolean false optional

                    Update operation is an upsert.

                    w number | string null optional

                    The write concern.

                    wtimeout number null optional

                    The write concern timeout.

                    j boolean false optional

                    Specify a journal write concern.

                    bypassDocumentValidation boolean false optional

                    Allow driver to bypass schema validation in MongoDB 3.2 or higher.

                    callback Collection~updateWriteOpCallback optional

                    The command result callback

                    Returns:
                    Promise if no callback passed
                    Examples
                    // Example of a simple document update with safe set to false on an existing document
                    
                    var MongoClient = require('mongodb').MongoClient,
                      test = require('assert');
                    MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                    
                      // Get a collection
                      var collection = db.collection('update_a_simple_document');
                    
                      // Insert a document, then update it
                      collection.insertOne({a:1}, {w:1}, function(err, doc) {
                    
                        // Update the document with an atomic operator
                        collection.updateOne({a:1}, {$set:{b:2}});
                    
                        // Wait for a second then fetch the document
                        setTimeout(function() {
                    
                          // Fetch the document that we modified
                          collection.findOne({a:1}, function(err, item) {
                            test.equal(null, err);
                            test.equal(1, item.a);
                            test.equal(2, item.b);
                            db.close();
                          });
                        }, 1000);
                      });
                    });
                    // Example of a simple document update using upsert (the document will be inserted if it does not exist)
                    
                    var MongoClient = require('mongodb').MongoClient,
                      test = require('assert');
                    MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                    
                      // Get a collection
                      var collection = db.collection('update_a_simple_document_upsert');
                      // Update the document using an upsert operation, ensuring creation if it does not exist
                      collection.updateOne({a:1}, {b:2, a:1}, {upsert:true, w: 1}, function(err, result) {
                        test.equal(null, err);
                        test.equal(1, result.result.n);
                    
                        // Fetch the document that we modified and check if it got inserted correctly
                        collection.findOne({a:1}, function(err, item) {
                          test.equal(null, err);
                          test.equal(1, item.a);
                          test.equal(2, item.b);
                          db.close();
                        });
                      });
                    });
                    // Example of a simple updateOne operation
                    
                    var MongoClient = require('mongodb').MongoClient,
                      test = require('assert');
                    MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                      // Get the collection
                      var col = db.collection('update_one');
                      col.updateOne({a:1}
                        , {$set: {a:2}}
                        , {upsert:true}, function(err, r) {
                        test.equal(null, err);
                        test.equal(0, r.matchedCount);
                        test.equal(1, r.upsertedCount);
                        // Finish up test
                        db.close();
                      });
                    });
                    // Example of a simple updateOne operation using a Promise.
                    
                    var MongoClient = require('mongodb').MongoClient,
                      test = require('assert');
                    MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                      // Get the collection
                      var col = db.collection('update_one_with_promise');
                      col.updateOne({a:1}
                        , {$set: {a:2}}
                        , {upsert:true}).then(function(r) {
                        test.equal(0, r.matchedCount);
                        test.equal(1, r.upsertedCount);
                        // Finish up test
                        db.close();
                      });
                    });
                    // Example of a simple updateOne operation 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');
                      // Get the collection
                      var col = db.collection('update_one_with_generators');
                      var r = yield col.updateOne({a:1}
                        , {$set: {a:2}}
                        , {upsert:true});
                      test.equal(0, r.matchedCount);
                      test.equal(1, r.upsertedCount);
                      // Finish up test
                      db.close();
                    });

                    Type Definitions

                    bulkWriteOpCallback(error, result)

                    The callback format for inserts

                    Name Type Description
                    error MongoError

                    An error instance representing the error during the execution.

                    result Collection~BulkWriteOpResult

                    The result object if the command was executed successfully.

                    BulkWriteOpResultObject

                    Properties:
                    Name Type Description
                    insertedCount number

                    Number of documents inserted.

                    matchedCount number

                    Number of documents matched for update.

                    modifiedCount number

                    Number of documents modified.

                    deletedCount number

                    Number of documents deleted.

                    upsertedCount number

                    Number of documents upserted.

                    insertedIds object

                    Inserted document generated Id's, hash key is the index of the originating operation

                    upsertedIds object

                    Upserted document generated Id's, hash key is the index of the originating operation

                    result object

                    The command result object.

                    collectionResultCallback(error, collection)

                    The callback format for the collection method, must be used if strict is specified

                    Name Type Description
                    error MongoError

                    An error instance representing the error during the execution.

                    collection Collection

                    The collection instance.

                    countCallback(error, result)

                    The callback format for results

                    Name Type Description
                    error MongoError

                    An error instance representing the error during the execution.

                    result number

                    The count of documents that matched the query.

                    deleteWriteOpCallback(error, result)

                    The callback format for inserts

                    Name Type Description
                    error MongoError

                    An error instance representing the error during the execution.

                    result Collection~deleteWriteOpResult

                    The result object if the command was executed successfully.

                    deleteWriteOpResultObject

                    Properties:
                    Name Type Description
                    result Object

                    The raw result returned from MongoDB, field will vary depending on server version.

                    Properties
                    Name Type Description
                    ok Number

                    Is 1 if the command executed correctly.

                    n Number

                    The total count of documents deleted.

                    connection Object

                    The connection object used for the operation.

                    deletedCount Number

                    The number of documents deleted.

                    findAndModifyCallback(error, result)

                    The callback format for inserts

                    Name Type Description
                    error MongoError

                    An error instance representing the error during the execution.

                    result Collection~findAndModifyWriteOpResult

                    The result object if the command was executed successfully.

                    findAndModifyWriteOpResultObject

                    Properties:
                    Name Type Description
                    value object

                    Document returned from findAndModify command.

                    lastErrorObject object

                    The raw lastErrorObject returned from the command.

                    ok Number

                    Is 1 if the command executed correctly.

                    insertOneWriteOpCallback(error, result)

                    The callback format for inserts

                    Name Type Description
                    error MongoError

                    An error instance representing the error during the execution.

                    result Collection~insertOneWriteOpResult

                    The result object if the command was executed successfully.

                    insertOneWriteOpResultObject

                    Properties:
                    Name Type Description
                    insertedCount Number

                    The total amount of documents inserted.

                    ops Array.<object>

                    All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany

                    insertedId ObjectId

                    The driver generated ObjectId for the insert operation.

                    connection object

                    The connection object used for the operation.

                    result object

                    The raw command result object returned from MongoDB (content might vary by server version).

                    Properties
                    Name Type Description
                    ok Number

                    Is 1 if the command executed correctly.

                    n Number

                    The total count of documents inserted.

                    insertWriteOpCallback(error, result)

                    The callback format for inserts

                    Name Type Description
                    error MongoError

                    An error instance representing the error during the execution.

                    result Collection~insertWriteOpResult

                    The result object if the command was executed successfully.

                    insertWriteOpResultObject

                    Properties:
                    Name Type Description
                    insertedCount Number

                    The total amount of documents inserted.

                    ops Array.<object>

                    All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany

                    insertedIds Array.<ObjectId>

                    All the generated _id's for the inserted documents.

                    connection object

                    The connection object used for the operation.

                    result object

                    The raw command result object returned from MongoDB (content might vary by server version).

                    Properties
                    Name Type Description
                    ok Number

                    Is 1 if the command executed correctly.

                    n Number

                    The total count of documents inserted.

                    parallelCollectionScanCallback(error, cursors)

                    The callback format for results

                    Name Type Description
                    error MongoError

                    An error instance representing the error during the execution.

                    cursors Array.<Cursor>

                    A list of cursors returned allowing for parallel reading of collection.

                    resultCallback(error, result)

                    The callback format for results

                    Name Type Description
                    error MongoError

                    An error instance representing the error during the execution.

                    result object

                    The result object if the command was executed successfully.

                    updateWriteOpCallback(error, result)

                    The callback format for inserts

                    Name Type Description
                    error MongoError

                    An error instance representing the error during the execution.

                    result Collection~updateWriteOpResult

                    The result object if the command was executed successfully.

                    updateWriteOpResultObject

                    Properties:
                    Name Type Description
                    result Object

                    The raw result returned from MongoDB, field will vary depending on server version.

                    Properties
                    Name Type Description
                    ok Number

                    Is 1 if the command executed correctly.

                    n Number

                    The total count of documents scanned.

                    nModified Number

                    The total count of documents modified.

                    connection Object

                    The connection object used for the operation.

                    matchedCount Number

                    The number of documents that matched the filter.

                    modifiedCount Number

                    The number of documents that were modified.

                    upsertedCount Number

                    The number of documents upserted.

                    upsertedId Object

                    The upserted id.

                    Properties
                    Name Type Description
                    _id ObjectId

                    The upserted _id returned from the server.

                    writeOpCallback(error, result)

                    The callback format for inserts

                    Name Type Description
                    error MongoError

                    An error instance representing the error during the execution.

                    result Collection~WriteOpResult

                    The result object if the command was executed successfully.

                    WriteOpResultObject

                    Properties:
                    Name Type Description
                    ops Array.<object>

                    All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany

                    connection object

                    The connection object used for the operation.

                    result object

                    The command result object.

                    comments powered by Disqus