Class: Db

Db

new Db(databaseName, topology, options){Db}

Creates a new Db instance

Name Type Default Description
databaseName string

The name of the database this instance represents.

topology Server | ReplSet | Mongos

The server topology for the database.

options object null optional

Optional settings.

Name Type Default Description
authSource string null optional

If the database authentication is dependent on another databaseName.

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.

forceServerObjectId boolean false optional

Force server to assign _id values instead of driver.

serializeFunctions boolean false optional

Serialize functions on any object.

ignoreUndefined Boolean false optional

Specify if the BSON serializer should ignore undefined fields.

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.

bufferMaxEntries number -1 optional

Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited.

readPreference ReadPreference | string null optional

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

pkFactory object null optional

A primary key factory object for generation of custom _id keys.

promiseLibrary object null optional

A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible

readConcern object null optional

Specify a read concern for the collection. (only MongoDB 3.2 or higher supported)

Name Type Default Description
level object 'local' optional

Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported)

Properties:
Name Type Description
serverConfig Server | ReplSet | Mongos

Get the current db topology.

bufferMaxEntries number

Current bufferMaxEntries value for the database

databaseName string

The name of the database this instance represents.

options object

The options associated with the db instance.

native_parser boolean

The current value of the parameter native_parser.

slaveOk boolean

The current slaveOk value for the db instance.

writeConcern object

The current write concern values.

topology object

Access the topology object (single server, replicaset or mongos).

Fires:
Returns:
Db instance.

Methods

addUser(username, password, options, callback){Promise}

Add a user to the database.

Name Type Default Description
username string

The username.

password string

The password.

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.

customData object null optional

Custom data associated with the user (only Mongodb 2.6 or higher)

roles Array.<object> null optional

Roles associated with the created user (only Mongodb 2.6 or higher)

callback Db~resultCallback optional

The command result callback

Returns:
Promise if no callback passed
Examples
// An example of adding a user to the database.

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

  // Add a user to the database
  db.addUser('user', 'name', function(err, result) {
    test.equal(null, err);

    // Remove the user from the db
    db.removeUser('user', function(err, result) {
      test.equal(null, err);

      db.close();
    });
  });
});
// An example of adding a user to the database using a Promise.

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Add a user to the database
  db.addUser('user', 'name').then(function(result) {

    // Remove the user from the db
    db.removeUser('user').then(function(result) {
      db.close();
    });
  });
});
// An example of adding a user to the database 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');
  // Add a user to the database
  yield db.addUser('user', 'name');

  // Remove the user from the db
  yield db.removeUser('user');
  db.close();
});

Return the Admin db instance

Returns:
the new Admin db instance
Example
// Example showing how to access the Admin database for admin level operations.

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

  // Use the admin database for the operation
  var adminDb = db.admin()
  test.ok(adminDb != null);

  db.close();
});

authenticate(username, password, options, callback){Promise}

Authenticate a user against the server.

Name Type Default Description
username string

The username.

password string optional

The password.

options object null optional

Optional settings.

Name Type Default Description
authMechanism string MONGODB-CR optional

The authentication mechanism to use, GSSAPI, MONGODB-CR, MONGODB-X509, PLAIN

callback Db~resultCallback optional

The command result callback

Returns:
Promise if no callback passed
Examples
// An example of using the authenticate command.

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

  // Add a user to the database
  db.addUser('user2', 'name', function(err, result) {
    test.equal(null, err);

    // Authenticate
    db.authenticate('user2', 'name', function(err, result) {
      test.equal(true, result);

      // Remove the user from the db
      db.removeUser('user2', function(err, result) {
        test.equal(null, err);

        db.close();
      });
    });
  });
});
// An example of using the authenticate command with a Promise.

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Add a user to the database
  db.addUser('user2', 'name').then(function(result) {

    // Authenticate
    db.authenticate('user2', 'name').then(function(result) {
      test.equal(true, result);

      // Remove the user from the db
      db.removeUser('user2').then(function(result) {
        db.close();
      });
    });
  });
});
// An example of using the authenticate command 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');
  // Add a user to the database
  yield db.addUser('user2', 'name');

  // Authenticate
  var result = yield db.authenticate('user2', 'name');
  test.equal(true, result);

  // Remove the user from the db
  yield db.removeUser('user2');
  db.close();
});

close(force, callback){Promise}

Close the db and its underlying connections

Name Type Description
force boolean

Force close, emitting no events

callback Db~noResultCallback optional

The result callback

Returns:
Promise if no callback passed
Examples
// An example that shows how to force close a db connection so it cannot be reused.

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

  // Fetch a collection
  var collection = db.collection('shouldCorrectlyFailOnRetryDueToAppCloseOfDb');

  // Insert a document
  collection.insertOne({a:1}, {w:1}, function(err, result) {
    test.equal(null, err);

    // Force close the connection
    db.close(true, function(err, result) {
      // Attemp to insert should fail now with correct message 'db closed by application'
      collection.insertOne({a:2}, {w:1}, function(err, result) {
        test.ok(err != null);

        db.close();
      });
    });
  });
});
// An example of a simple single server db connection and close function

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

  // Close the connection with a callback that is optional
  db.close(function(err, result) {
    test.equal(null, err);

  });
});
// An example that shows how to force close a db connection so it cannot be reused using a Promise..

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

  // Fetch a collection
  var collection = db.collection('shouldCorrectlyFailOnRetryDueToAppCloseOfDb_with_promise');
  // Insert a document
  collection.insertOne({a:1}, {w:1}).then(function(result) {

    // Force close the connection
    db.close(true).then(function() {
      // Attemp to insert should fail now with correct message 'db closed by application'
      collection.insertOne({a:2}, {w:1}).then(function(result) {
      }).catch(function(err) {
        db.close();
      });
    });
  });
});
// An example of a simple single server db connection and close function using a Promise.

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

  // Close the connection with a callback that is optional
  db.close().then(function(result) {
  });
});
// An example that shows how to force close a db connection so it cannot be reused 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
  var collection = db.collection('shouldCorrectlyFailOnRetryDueToAppCloseOfDb_with_generators');
  // Insert a document
  yield collection.insertOne({a:1}, {w:1});

  // Force close the connection
  yield db.close(true)

  try {
    // Attemp to insert should fail now with correct message 'db closed by application'
    yield collection.insertOne({a:2}, {w:1});
  } catch(err) {
    db.close();
  }
});

collection(name, options, callback){Collection}

Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you can
can use it without a callback in the following way: var collection = db.collection('mycollection');

Name Type Default Description
name string

the collection name we wish to access.

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.

raw boolean false optional

Return document results as raw BSON buffers.

pkFactory object null optional

A primary key factory object for generation of custom _id keys.

readPreference ReadPreference | string null optional

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

serializeFunctions boolean false optional

Serialize functions on any object.

strict boolean false optional

Returns an error if the collection does not exist

readConcern object null optional

Specify a read concern for the collection. (only MongoDB 3.2 or higher supported)

Name Type Default Description
level object 'local' optional

Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported)

callback Db~collectionResultCallback

The collection result callback

Returns:
the new Collection instance if not in strict mode
Examples
// An example of retrieving a collection from a db using the collection function.

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

  // Grab a collection without a callback no safe mode
  var col1 = db.collection('test_correctly_access_collections');

  // Grab a collection with a callback but no safe operation
  db.collection('test_correctly_access_collections', function(err, col2) {
    test.equal(null, err);

    // Grab a collection with a callback in safe mode, ensuring it exists (should fail as it's not created)
    db.collection('test_correctly_access_collections', {strict:true}, function(err, col3) {
      test.ok(err != null);

      // Create the collection
      db.createCollection('test_correctly_access_collections', function(err, result) {

        // Retry to get the collection, should work as it's now created
        db.collection('test_correctly_access_collections', {strict:true}, function(err, col3) {
          test.equal(null, err);

          db.close();
        });
      });
    });
  });
});
// An example of retrieving a collection from a db using the collection function with a Promise.

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Grab a collection without a callback no safe mode
  var col1 = db.collection('test_correctly_access_collections_with_promise');
  // Grab a collection with a callback but no safe operation
  db.collection('test_correctly_access_collections_with_promise', function(err, col2) {

    // Grab a collection with a callback in safe mode, ensuring it exists (should fail as it's not created)
    db.collection('test_correctly_access_collections_with_promise', {strict:true}, function(err, col3) {
      // Create the collection
      db.createCollection('test_correctly_access_collections_with_promise').then(function(err, result) {

        // Retry to get the collection, should work as it's now created
        db.collection('test_correctly_access_collections_with_promise', {strict:true}, function(err, col3) {
          db.close();
        });
      });
    });
  });
});

collections(callback){Promise}

Fetch all collections for the current db.

Name Type Description
callback Db~collectionsResultCallback optional

The results callback

Returns:
Promise if no callback passed
Examples
// An example of retrieving all collections for a db as Collection objects

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

  // Create the collection
  var collection = db.collection('test_correctly_access_collections2');
  // Retry to get the collection, should work as it's now created
  db.collections(function(err, collections) {
    test.equal(null, err);
    test.ok(collections.length > 0);

    db.close();
  });
});
// An example of retrieving all collections for a db as Collection objects using a Promise.

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Create the collection
  var collection = db.collection('test_correctly_access_collections2_with_promise');
  // Retry to get the collection, should work as it's now created
  db.collections().then(function(collections) {
    test.ok(collections.length > 0);

    db.close();
  });
});
// An example of retrieving all collections for a db as Collection objects 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 the collection
  var collection = db.collection('test_correctly_access_collections2_with_generators');
  // Retry to get the collection, should work as it's now created
  var collections = yield db.collections();
  test.ok(collections.length > 0);

  db.close();
});

command(command, options, callback){Promise}

Execute a command

Name Type Default Description
command object

The command hash

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 Db~resultCallback optional

The command result callback

Returns:
Promise if no callback passed
Examples
// A simple example executing a command against the server.

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

  // Execute ping against the server
  db.command({ping:1}, function(err, result) {
    test.equal(null, err);

    db.close();
  });
});
// A simple example executing a command against the server using a Promise.

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Execute ping against the server
  db.command({ping:1}).then(function(result) {
    db.close();
  });
});
// A simple example executing a command against the server 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');
  // Execute ping against the server
  yield db.command({ping:1});
  db.close();
});

createCollection(name, options, callback){Promise}

Create a new collection on a server with the specified options. Use this to create capped collections.

Name Type Default Description
name string

the collection name we wish to access.

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.

raw boolean false optional

Return document results as raw BSON buffers.

pkFactory object null optional

A primary key factory object for generation of custom _id keys.

readPreference ReadPreference | string null optional

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

serializeFunctions boolean false optional

Serialize functions on any object.

strict boolean false optional

Returns an error if the collection does not exist

capped boolean false optional

Create a capped collection.

size number null optional

The size of the capped collection in bytes.

max number null optional

The maximum number of documents in the capped collection.

autoIndexId boolean true optional

Create an index on the _id field of the document, True by default on MongoDB 2.2 or higher off for version < 2.2.

callback Db~collectionResultCallback optional

The results callback

Returns:
Promise if no callback passed
Examples
// A simple example showing the creation of a collection.

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

  // Create a capped collection with a maximum of 1000 documents
  db.createCollection("a_simple_collection", {capped:true, size:10000, max:1000, w:1}, function(err, collection) {
    test.equal(null, err);

    // Insert a document in the capped collection
    collection.insertOne({a:1}, {w:1}, function(err, result) {
      test.equal(null, err);

      db.close();
    });
  });
});
// A simple example showing the listening to a capped collection

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

  // Create a capped collection with a maximum of 1000 documents
  db.createCollection("a_simple_collection_2", {capped:true, size:100000, max:10000, w:1}, function(err, collection) {
    test.equal(null, err);

    var docs = [];
    for(var i = 0; i < 1000; i++) docs.push({a:i});

    // Insert a document in the capped collection
    collection.insertMany(docs, {w:1}, function(err, result) {

      // Start date
      var s = new Date();
      var total = 0;

      // Get the cursor
      var cursor = collection.find({})
        .addCursorFlag('tailable', true)
        .addCursorFlag('awaitData', true);

      cursor.on('data', function() {
        total = total + 1;

        if(total == 1000) {
          cursor.kill();
        }
      });

      cursor.on('end', function() {
        db.close();
      });
    });
  });
});
// A simple example showing the creation 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 capped collection with a maximum of 1000 documents
  db.createCollection("a_simple_collection_with_promise", {capped:true, size:10000, max:1000, w:1}).then(function(collection) {

    // Insert a document in the capped collection
    collection.insertOne({a:1}, {w:1}).then(function(result) {
      db.close();
    });
  });
});
// A simple example showing the listening to 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 capped collection with a maximum of 1000 documents
  db.createCollection("a_simple_collection_2_with_promise", {capped:true, size:100000, max:10000, w:1}).then(function(collection) {
    var docs = [];
    for(var i = 0; i < 1000; i++) docs.push({a:i});

    // Insert a document in the capped collection
    collection.insertMany(docs, {w:1}).then(function(result) {
      // Start date
      var s = new Date();
      var total = 0;

      // Get the cursor
      var cursor = collection.find({a: {$gte:0}})
        .addCursorFlag('tailable', true)
        .addCursorFlag('awaitData', true)

      cursor.on('data', function(d) {
        total = total + 1;

        if(total == 1000) {
          cursor.kill();
        }
      });

      cursor.on('end', function() {
        test.ok((new Date().getTime() - s.getTime()) > 1000);

        db.close();
      });
    });
  });
});
// A simple example showing the creation 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 capped collection with a maximum of 1000 documents
  var collection = yield db.createCollection("a_simple_collection_with_generators", {capped:true, size:10000, max:1000, w:1});

  // Insert a document in the capped collection
  yield collection.insertOne({a:1}, {w:1});
  db.close();
});
// A simple example showing the listening to 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 capped collection with a maximum of 1000 documents
  var collection = yield db.createCollection("a_simple_collection_2_with_generators", {capped:true, size:100000, max:10000, w:1});
  var docs = [];
  for(var i = 0; i < 1000; i++) docs.push({a:i});

  // Insert a document in the capped collection
  yield collection.insertMany(docs, {w:1});
  // Start date
  var s = new Date();
  var total = 0;

  // Get the cursor
  var cursor = collection.find({})
    .addCursorFlag('tailable', true)
    .addCursorFlag('awaitData', true)

  cursor.on('data', function() {
    total = total + 1;

    if(total == 1000) {
      cursor.kill();
    }
  });

  cursor.on('end', function() {
    db.close();
  });
});

createIndex(name, fieldOrSpec, options, callback){Promise}

Creates an index on the db and collection collection.

Name Type Default Description
name string

Name of the collection to create the index on.

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)

partialFilterExpression object null optional

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

callback Db~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('more_complex_index_test');
  // 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.createIndex('more_complex_index_test', {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);

        // Peform 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 and dropping duplicated documents 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_complex_index_test_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.createIndex('more_complex_index_test_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);

        // Peform 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 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');

  // Create a collection we want to drop later
  var collection = db.collection('more_complex_index_test_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.createIndex('more_complex_index_test_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);

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

  db.close();
});

db(name, options){Db}

Create a new Db instance sharing the current socket connections. Be aware that the new db instances are
related in a parent-child relationship to the original instance so that events are correctly emitted on child
db instances. Child db instances are cached so performing db('db1') twice will return the same instance.
You can control these behaviors with the options noListener and returnNonCachedInstance.

Name Type Default Description
name string

The name of the database we want to use.

options object null optional

Optional settings.

Name Type Default Description
noListener boolean false optional

Do not make the db an event listener to the original connection.

returnNonCachedInstance boolean false optional

Control if you want to return a cached instance or have a new one created

Examples
// Simple example connecting to two different databases sharing the socket connections below.

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

  // Reference a different database sharing the same connections
  // for the data transfer
  var secondDb = db.db("integration_tests_2");

  // Fetch the collections
  var multipleColl1 = db.collection("multiple_db_instances");
  var multipleColl2 = secondDb.collection("multiple_db_instances");

  // Write a record into each and then count the records stored
  multipleColl1.insertOne({a:1}, {w:1}, function(err, result) {
    multipleColl2.insertOne({a:1}, {w:1}, function(err, result) {

      // Count over the results ensuring only on record in each collection
      multipleColl1.count(function(err, count) {
        test.equal(1, count);

        multipleColl2.count(function(err, count) {
          test.equal(1, count);

          db.close();
        });
      });
    });
  });
});
// Simple example connecting to two different databases sharing the socket connections below using a Promise.

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Reference a different database sharing the same connections
  // for the data transfer
  var secondDb = db.db("integration_tests_2");

  // Fetch the collections
  var multipleColl1 = db.collection("multiple_db_instances_with_promise");
  var multipleColl2 = secondDb.collection("multiple_db_instances_with_promise");

  // Write a record into each and then count the records stored
  multipleColl1.insertOne({a:1}, {w:1}).then(function(result) {
    multipleColl2.insertOne({a:1}, {w:1}).then(function(result) {

      // Count over the results ensuring only on record in each collection
      multipleColl1.count().then(function(count) {
        test.equal(1, count);

        multipleColl2.count().then(function(count) {
          test.equal(1, count);

          db.close();
        });
      });
    });
  });
});
// Simple example connecting to two different databases sharing the socket connections below 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');
  // Reference a different database sharing the same connections
  // for the data transfer
  var secondDb = db.db("integration_tests_2");

  // Fetch the collections
  var multipleColl1 = db.collection("multiple_db_instances_with_generators");
  var multipleColl2 = secondDb.collection("multiple_db_instances_with_generators");

  // Write a record into each and then count the records stored
  yield multipleColl1.insertOne({a:1}, {w:1});
  yield multipleColl2.insertOne({a:1}, {w:1})

  // Count over the results ensuring only on record in each collection
  var count = yield multipleColl1.count();
  test.equal(1, count);

  var count = yield multipleColl2.count();
  test.equal(1, count);

  db.close();
});

dropCollection(name, callback){Promise}

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

Name Type Description
name string

Name of collection to drop

callback Db~resultCallback optional

The results callback

Returns:
Promise if no callback passed
Examples
// A simple example creating, dropping a collection and then verifying that the collection is gone.

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

  // Execute ping against the server
  db.command({ping:1}, function(err, result) {
    test.equal(null, err);

    // Create a capped collection with a maximum of 1000 documents
    db.createCollection("a_simple_create_drop_collection", {capped:true, size:10000, max:1000, w:1}, function(err, collection) {
      test.equal(null, err);

      // Insert a document in the capped collection
      collection.insertOne({a:1}, {w:1}, function(err, result) {
        test.equal(null, err);

        // Drop the collection from this world
        db.dropCollection("a_simple_create_drop_collection", function(err, result) {
          test.equal(null, err);

          // Verify that the collection is gone
          db.listCollections({name:"a_simple_create_drop_collection"}).toArray(function(err, names) {
            test.equal(0, names.length);

            db.close();
          });
        });
      });
    });
  });
});
// A simple example creating, dropping a collection and then verifying that the collection is gone using a Promise.

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Execute ping against the server
  db.command({ping:1}).then(function(result) {

    // Create a capped collection with a maximum of 1000 documents
    db.createCollection("a_simple_create_drop_collection_with_promise", {capped:true, size:10000, max:1000, w:1}).then(function(collection) {

      // Insert a document in the capped collection
      collection.insertOne({a:1}, {w:1}).then(function(result) {

        // Drop the collection from this world
        db.dropCollection("a_simple_create_drop_collection_with_promise").then(function(result) {

          // Verify that the collection is gone
          db.listCollections({name:"a_simple_create_drop_collection_with_promise"}).toArray().then(function(names) {
            test.equal(0, names.length);

            db.close();
          });
        });
      });
    });
  });
});
// A simple example creating, dropping a collection and then verifying that the collection is gone 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');
  // Execute ping against the server
  yield db.command({ping:1});

  // Create a capped collection with a maximum of 1000 documents
  var collection = yield db.createCollection("a_simple_create_drop_collection_with_generators", {capped:true, size:10000, max:1000, w:1});

  // Insert a document in the capped collection
  yield collection.insertOne({a:1}, {w:1});

  // Drop the collection from this world
  yield db.dropCollection("a_simple_create_drop_collection_with_generators");

  // Verify that the collection is gone
  var names = yield db.listCollections({name:"a_simple_create_drop_collection_with_generators"}).toArray();
  test.equal(0, names.length);

  db.close();
});

dropDatabase(callback){Promise}

Drop a database, removing it permanently from the server.

Name Type Description
callback Db~resultCallback optional

The results callback

Returns:
Promise if no callback passed
Examples
// An examples showing the dropping of a database

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

  // Create a collection
  var collection = db.collection('more_index_information_test_1');
  // Insert a bunch of documents for the index
  collection.insertMany([{a:1, b:1}, {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);

    // Let's drop the database
    db.dropDatabase(function(err, result) {
      test.equal(null, err);

      // Wait to seconds to let it replicate across
      setTimeout(function() {
        // Get the admin database
        db.admin().listDatabases(function(err, dbs) {
          // Grab the databases
          dbs = dbs.databases;
          // Did we find the db
          var found = false;

          // Check if we have the db in the list
          for(var i = 0; i < dbs.length; i++) {
            if(dbs[i].name == 'integration_tests_to_drop') found = true;
          }

          // We should not find the databases
          if(process.env['JENKINS'] == null) test.equal(false, found);

          db.close();
        });
      }, 2000);
    });
  });
});
// An examples showing the dropping of a database using a Promise.

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

  // Create a collection
  var collection = db.collection('more_index_information_test_1_with_promise');
  // Insert a bunch of documents for the index
  collection.insertMany([{a:1, b:1}, {a:1, b:1}
    , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1}).then(function(result) {

    // Let's drop the database
    db.dropDatabase().then(function(result) {

      // Wait to seconds to let it replicate across
      setTimeout(function() {
        // Get the admin database
        db.admin().listDatabases().then(function(dbs) {
          // Grab the databases
          dbs = dbs.databases;
          // Did we find the db
          var found = false;

          // Check if we have the db in the list
          for(var i = 0; i < dbs.length; i++) {
            if(dbs[i].name == 'integration_tests_to_drop') found = true;
          }

          // We should not find the databases
          if(process.env['JENKINS'] == null) test.equal(false, found);

          db.close();
        });
      }, 2000);
    });
  });
});
// An examples showing the dropping of a database 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
  var collection = db.collection('more_index_information_test_1_with_generators');
  // Insert a bunch of documents for the index
  yield collection.insertMany([{a:1, b:1}, {a:1, b:1}
    , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {w:1});

  // Let's drop the database
  yield db.dropDatabase();

  // Wait to seconds to let it replicate across
  setTimeout(function() {
    co(function*() {
      // Get the admin database
      var dbs = yield db.admin().listDatabases();
      // Grab the databases
      dbs = dbs.databases;
      // Did we find the db
      var found = false;

      // Check if we have the db in the list
      for(var i = 0; i < dbs.length; i++) {
        if(dbs[i].name == 'integration_tests_to_drop') found = true;
      }

      // We should not find the databases
      if(process.env['JENKINS'] == null) test.equal(false, found);

      db.close();
    });
  }, 2000);
});

ensureIndex(name, fieldOrSpec, options, callback){Promise}

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

Name Type Default Description
name string

The index name

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)

callback Db~resultCallback optional

The command result callback

Deprecated
  • since version 2.0
    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) {
    
      // Create a collection we want to drop later
      var collection = db.collection('more_complex_ensure_index_db_test');
      // 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('more_complex_ensure_index_db_test', {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);
    
            // Peform 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) {
    
      // Create a collection we want to drop later
      var collection = db.collection('more_complex_ensure_index_db_test_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('more_complex_ensure_index_db_test_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);
    
            // Peform 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');
    
      // Create a collection we want to drop later
      var collection = db.collection('more_complex_ensure_index_db_test_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('more_complex_ensure_index_db_test_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);
    
      // Peform a query, with explain to show we hit the query
      var explanation = yield collection.find({a:2}).explain();
      test.ok(explanation != null);
    
      db.close();
    });

    eval(code, parameters, options, callback){Promise}

    Evaluate JavaScript on the server

    Name Type Default Description
    code Code

    JavaScript to execute on server.

    parameters object | array

    The parameters for the call.

    options object null optional

    Optional settings.

    Name Type Default Description
    nolock boolean false optional

    Tell MongoDB not to block on the evaulation of the javascript.

    callback Db~resultCallback optional

    The results callback

    Deprecated
    • Eval is deprecated on MongoDB 3.2 and forward
      Returns:
      Promise if no callback passed
      Examples
      // A whole bunch of examples on how to use eval on the server.
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
        var numberOfTests = 10;
      
        var tests_done = function() {
          numberOfTests = numberOfTests - 1;
      
          if(numberOfTests == 0) {
            db.close();
          }
        }
      
        // Evaluate a function on the server with the parameter 3 passed in
        db.eval('function (x) {return x;}', [3], function(err, result) {
          test.equal(3, result); tests_done();
      
          // Evaluate a function on the server with the parameter 3 passed in no lock aquired for eval
          // on server
          db.eval('function (x) {return x;}', [3], {nolock:true}, function(err, result) {
            test.equal(3, result); tests_done();
          });
      
          // Evaluate a function on the server that writes to a server collection
          db.eval('function (x) {db.test_eval.save({y:x});}', [5], {readPreference: ReadPreference.PRIMARY}, function(err, result) {
            setTimeout(function() {
              // Locate the entry
              db.collection('test_eval', function(err, collection) {
                collection.findOne(function(err, item) {
                  test.equal(5, item.y); tests_done();
      
                  // Evaluate a function with 2 parameters passed in
                  db.eval('function (x, y) {return x + y;}', [2, 3], function(err, result) {
                    test.equal(5, result); tests_done();
      
                    // Evaluate a function with no parameters passed in
                    db.eval('function () {return 5;}', function(err, result) {
                      test.equal(5, result); tests_done();
      
                      // Evaluate a statement
                      db.eval('2 + 3;', function(err, result) {
                        test.equal(5, result); tests_done();
      
                        // Evaluate a statement using the code object
                        db.eval(new Code("2 + 3;"), function(err, result) {
                          test.equal(5, result); tests_done();
      
                          // Evaluate a statement using the code object including a scope
                          db.eval(new Code("return i;", {'i':2}), function(err, result) {
                            test.equal(2, result); tests_done();
      
                            // Evaluate a statement using the code object including a scope
                            db.eval(new Code("i + 3;", {'i':2}), function(err, result) {
                              test.equal(5, result); tests_done();
      
                              // Evaluate an illegal statement
                              db.eval("5 ++ 5;", function(err, result) {
                                test.ok(err instanceof Error);
                                test.ok(err.message != null);
                                tests_done();
                                // Let's close the db
                                // db.close();
                              });
                            });
                          });
                        });
                      });
                    });
                  });
                });
              });
            }, 1000);
          });
        });
      });
      // Defining and calling a system level javascript function (NOT recommended, http://www.mongodb.org/display/DOCS/Server-side+Code+Execution)
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
      
        // Clean out the collection
        db.collection("system.js").deleteMany({}, {w:1}, function(err, result) {
          test.equal(null, err);
      
          // Define a system level function
          db.collection("system.js").insertOne({_id: "echo", value: new Code("function(x) { return x; }")}, {w:1}, function(err, result) {
            test.equal(null, err);
      
            db.eval("echo(5)", function(err, result) {
              test.equal(null, err);
              test.equal(5, result);
      
              db.close();
            });
          });
        });
      });
      // A whole bunch of examples on how to use eval on the server with a Promise.
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
        var numberOfTests = 10;
      
        var tests_done = function() {
          numberOfTests = numberOfTests - 1;
      
          if(numberOfTests == 0) {
            db.close();
          }
        }
      
        // Evaluate a function on the server with the parameter 3 passed in
        db.eval('function (x) {return x;}', [3]).then(function(result) {
          test.equal(3, result); tests_done();
      
          // Evaluate a function on the server with the parameter 3 passed in no lock aquired for eval
          // on server
          db.eval('function (x) {return x;}', [3], {nolock:true}).then(function(result) {
            test.equal(3, result); tests_done();
          });
      
          // Evaluate a function on the server that writes to a server collection
          db.eval('function (x) {db.test_eval_with_promise.save({y:x});}', [5], {readPreference: ReadPreference.PRIMARY}).then(function(result) {
            setTimeout(function() {
              // Locate the entry
              db.collection('test_eval_with_promise', function(err, collection) {
                collection.findOne().then(function(item) {
                  test.equal(5, item.y); tests_done();
      
                  // Evaluate a function with 2 parameters passed in
                  db.eval('function (x, y) {return x + y;}', [2, 3]).then(function(result) {
                    test.equal(5, result); tests_done();
      
                    // Evaluate a function with no parameters passed in
                    db.eval('function () {return 5;}').then(function(result) {
                      test.equal(5, result); tests_done();
      
                      // Evaluate a statement
                      db.eval('2 + 3;').then(function(result) {
                        test.equal(5, result); tests_done();
      
                        // Evaluate a statement using the code object
                        db.eval(new Code("2 + 3;")).then(function(result) {
                          test.equal(5, result); tests_done();
      
                          // Evaluate a statement using the code object including a scope
                          db.eval(new Code("return i;", {'i':2})).then(function(result) {
                            test.equal(2, result); tests_done();
      
                            // Evaluate a statement using the code object including a scope
                            db.eval(new Code("i + 3;", {'i':2})).then(function(result) {
                              test.equal(5, result); tests_done();
      
                              // Evaluate an illegal statement
                              db.eval("5 ++ 5;").then(function(result) {
                              }).catch(function(err) {
                                test.ok(err instanceof Error);
                                test.ok(err.message != null);
                                tests_done();
                              });
                            });
                          });
                        });
                      });
                    });
                  });
                });
              });
            }, 1000);
          });
        });
      });
      // Defining and calling a system level javascript function (NOT recommended, http://www.mongodb.org/display/DOCS/Server-side+Code+Execution) using a Promise.
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
      
        // Clean out the collection
        db.collection("system.js").deleteMany({}, {w:1}).then(function(result) {
      
          // Define a system level function
          db.collection("system.js").insertOne({_id: "echo", value: new Code("function(x) { return x; }")}, {w:1}).then(function(result) {
      
            db.eval("echo(5)").then(function(result) {
              test.equal(5, result);
      
              db.close();
            });
          });
        });
      });
      // A whole bunch of examples on how to use eval on the server 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');
        var numberOfTests = 10;
      
        var tests_done = function() {
          numberOfTests = numberOfTests - 1;
      
          if(numberOfTests == 0) {
            db.close();
          }
        }
      
        // Evaluate a function on the server with the parameter 3 passed in
        var result = yield db.eval('function (x) {return x;}', [3]);
        test.equal(3, result); tests_done();
      
        // Evaluate a function on the server with the parameter 3 passed in no lock aquired for eval
        // on server
        var result = yield db.eval('function (x) {return x;}', [3], {nolock:true})
        test.equal(3, result); tests_done();
      
        // Evaluate a function on the server that writes to a server collection
        var result = yield db.eval('function (x) {db.test_eval_with_generators.save({y:x});}', [5], {readPreference: ReadPreference.PRIMARY});
        setTimeout(function() {
          co(function*() {
            // Locate the entry
            var collection = db.collection('test_eval_with_generators');
            var item = yield collection.findOne();
            test.equal(5, item.y); tests_done();
      
            // Evaluate a function with 2 parameters passed in
            var result = yield db.eval('function (x, y) {return x + y;}', [2, 3]);
            test.equal(5, result); tests_done();
      
            // Evaluate a function with no parameters passed in
            var result = yield db.eval('function () {return 5;}');
            test.equal(5, result); tests_done();
      
            // Evaluate a statement
            var result = yield db.eval('2 + 3;');
            test.equal(5, result); tests_done();
      
            // Evaluate a statement using the code object
            var result = yield db.eval(new Code("2 + 3;"));
            test.equal(5, result); tests_done();
      
            // Evaluate a statement using the code object including a scope
            var result = yield db.eval(new Code("return i;", {'i':2}))
            test.equal(2, result); tests_done();
      
            // Evaluate a statement using the code object including a scope
            var result = yield db.eval(new Code("i + 3;", {'i':2}));
            test.equal(5, result); tests_done();
      
            try {
              // Evaluate an illegal statement
              yield db.eval("5 ++ 5;");
            } catch(err) {
              test.ok(err instanceof Error);
              test.ok(err.message != null);
              tests_done();
            }
          });
        }, 1000);
      });
      // Defining and calling a system level javascript function (NOT recommended, http://www.mongodb.org/display/DOCS/Server-side+Code+Execution) 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');
      
        // Clean out the collection
        yield db.collection("system.js").deleteMany({}, {w:1});
      
        // Define a system level function
        yield db.collection("system.js").insertOne({_id: "echo", value: new Code("function(x) { return x; }")}, {w:1});
      
        var result = yield db.eval("echo(5)");
        test.equal(5, result);
      
        db.close();
      });

      executeDbAdminCommand(command, options, callback){Promise}

      Runs a command on the database as admin.

      Name Type Default Description
      command object

      The command hash

      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 Db~resultCallback optional

      The command result callback

      Returns:
      Promise if no callback passed

      indexInformation(name, options, callback){Promise}

      Retrieves this collections index info.

      Name Type Default Description
      name string

      The name of the collection.

      options object null optional

      Optional settings.

      Name Type Default Description
      full boolean false optional

      Returns the full raw index information.

      readPreference ReadPreference | string null optional

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

      callback Db~resultCallback optional

      The command result callback

      Returns:
      Promise if no callback passed

      listCollections(filter, options){CommandCursor}

      Get the list of all collection information for the specified db.

      Name Type Default Description
      filter object

      Query to filter collections by

      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).

      Examples
      // An example of retrieving the collections list for a database.
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
        test.equal(null, err);
      
        // Get an empty db
        var db1 = db.db('listCollectionTestDb');
        // Create a collection
        var collection = db1.collection('shouldCorrectlyRetrievelistCollections');
        // Ensure the collection was created
        collection.insertOne({a:1}, function(err, r) {
          test.equal(null, err);
      
          // Return the information of a single collection name
          db1.listCollections({name: "shouldCorrectlyRetrievelistCollections"}).toArray(function(err, items) {
            test.equal(1, items.length);
      
            // Return the information of a all collections, using the callback format
            db1.listCollections().toArray(function(err, items) {
              test.ok(items.length >= 1);
      
              db.close();
            });
          });
        });
      });
      // An example of retrieving the collections list for a database using a Promise.
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
        // Get an empty db
        var db1 = db.db('listCollectionTestDb2');
        // Create a collection
        var collection = db1.collection('shouldCorrectlyRetrievelistCollections_with_promise');
        // Ensure the collection was created
        collection.insertOne({a:1}).then(function(r) {
      
          // Return the information of a single collection name
          db1.listCollections({name: "shouldCorrectlyRetrievelistCollections_with_promise"}).toArray().then(function(items) {
            test.equal(1, items.length);
      
            // Return the information of a all collections, using the callback format
            db1.listCollections().toArray().then(function(items) {
              test.ok(items.length >= 1);
      
              db.close();
            });
          }).catch(function(err) {
            console.dir(err)
          });
        });
      });
      // An example of retrieving the collections list for a database 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 an empty db
        var db1 = db.db('listCollectionTestDb2Generator');
        // Create a collection
        var collection = db1.collection('shouldCorrectlyRetrievelistCollections_with_generators');
        // Ensure the collection was created
        yield collection.insertOne({a:1});
      
        // Return the information of a single collection name
        var items = yield db1.listCollections({name: "shouldCorrectlyRetrievelistCollections_with_generators"}).toArray();
        test.equal(1, items.length);
      
        // Return the information of a all collections, using the callback format
        var items = yield db1.listCollections().toArray();
        test.ok(items.length >= 1);
      
        db.close();
      });

      logout(options, callback){Promise}

      Logout user from server, fire off on all connections and remove all auth info

      Name Type Default Description
      options object null optional

      Optional settings.

      Name Type Default Description
      dbName string null optional

      Logout against different database than current.

      callback Db~resultCallback optional

      The command result callback

      Returns:
      Promise if no callback passed
      Examples
      // An example of using the logout command for the database.
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
        test.equal(null, err);
      
        // Add a user to the database
        db.addUser('user3', 'name', function(err, result) {
          test.equal(null, err);
      
          // Authenticate
          db.authenticate('user3', 'name', function(err, result) {
            test.equal(true, result);
      
            // Logout the db
            db.logout(function(err, result) {
              test.equal(true, result);
      
              // Remove the user
              db.removeUser('user3', function(err, result) {
                test.equal(true, result);
      
                db.close();
              });
            });
          });
        });
      });
      // An example of using the logout command for the database with a Promise.
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
        // Add a user to the database
        db.addUser('user3', 'name').then(function(result) {
      
          // Authenticate
          db.authenticate('user3', 'name').then(function(result) {
            test.equal(true, result);
      
            // Logout the db
            db.logout().then(function(result) {
              test.equal(true, result);
      
              // Remove the user
              db.removeUser('user3').then(function(result) {
                test.equal(true, result);
      
                db.close();
              }).catch(function(err) {
                console.dir(err)
              });
            });
          });
        });
      });
      // An example of using the logout command for the database 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');
        // Add a user to the database
        var result = yield db.addUser('user3', 'name')
      
        // Authenticate
        var result = yield db.authenticate('user3', 'name');
        test.equal(true, result);
      
        // Logout the db
        var result = yield db.logout()
        test.equal(true, result);
      
        // Remove the user
        var result = yield db.removeUser('user3');
        test.equal(true, result);
      
        db.close();
      });

      open(callback){Promise}

      Open the database

      Name Type Description
      callback Db~openCallback optional

      Callback

      Returns:
      Promise if no callback passed
      Examples
      // An example of a simple single server db connection
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
        test.equal(null, err);
      
        db.on('close', function() {
        })
      
        db.close();
      });
      // Simple replicaset connection setup, requires a running replicaset on the correct ports
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
        test.equal(null, err);
        p_db.close();
      });
      // Simple replicaset connection setup, requires a running replicaset on the correct ports using a Promise.
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
        p_db.close();
      });

      removeUser(username, options, callback){Promise}

      Remove a user from a database

      Name Type Default Description
      username string

      The username.

      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 Db~resultCallback optional

      The command result callback

      Returns:
      Promise if no callback passed
      Examples
      // An example of removing a user.
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
        test.equal(null, err);
      
        // Add a user to the database
        db.addUser('user', 'name', function(err, result) {
          test.equal(null, err);
      
          // Authenticate
          db.authenticate('user', 'name', function(err, result) {
            test.equal(true, result);
      
            // Logout the db
            db.logout(function(err, result) {
              test.equal(true, result);
      
              // Remove the user from the db
              db.removeUser('user', function(err, result) {
      
                // Authenticate
                db.authenticate('user', 'name', function(err, result) {
                  test.equal(false, result);
      
                  db.close();
                });
              });
            });
          });
        });
      });
      // An example of removing a user using a Promise.
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
      
        // Add a user to the database
        db.addUser('user', 'name').then(function(result) {
      
          // Authenticate
          db.authenticate('user', 'name').then(function(result) {
            test.equal(true, result);
      
            // Logout the db
            db.logout().then(function(result) {
              test.equal(true, result);
      
              // Remove the user from the db
              db.removeUser('user').then(function(result) {
      
                // Authenticate
                db.authenticate('user', 'name').then(function(result) {
                  test.equal(false, result);
      
                  db.close();
                }).catch(function(err) {
                  db.close();
                });
              });
            });
          });
        });
      });
      // An example of removing a user 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');
      
        // Add a user to the database
        yield db.addUser('user', 'name');
      
        // Authenticate
        var result = yield db.authenticate('user', 'name');
        test.equal(true, result);
      
        // Logout the db
        var result = yield db.logout();
        test.equal(true, result);
      
        // Remove the user from the db
        yield db.removeUser('user');
      
        try {
          // Authenticate
          var result = yield db.authenticate('user', 'name');
          assert.ok(false);
        } catch(err) {}
      
        db.close();
      }).catch(function(err) {
        console.log(err.stack)
      });

      renameCollection(fromCollection, toCollection, options, callback){Promise}

      Rename a collection.

      Name Type Default Description
      fromCollection string

      Name of current collection to rename.

      toCollection 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 Db~collectionResultCallback optional

      The results callback

      Returns:
      Promise if no callback passed
      Examples
      // A simple example creating, dropping a collection and then verifying that the collection is gone.
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
        test.equal(null, err);
      
        // Create a collection
        db.createCollection("simple_rename_collection", {w:1}, function(err, collection) {
          test.equal(null, err);
      
          // Insert a document in the collection
          collection.insertOne({a:1}, {w:1}, function(err, result) {
            test.equal(null, err);
      
            // Retrieve the number of documents from the collection
            collection.count(function(err, count) {
              test.equal(1, count);
      
              // Rename the collection
              db.renameCollection("simple_rename_collection", "simple_rename_collection_2", function(err, collection2) {
                test.equal(null, err);
      
                // Retrieve the number of documents from the collection
                collection2.count(function(err, count) {
                  test.equal(1, count);
      
                  // Verify that the collection is gone
                  db.listCollections({name:"simple_rename_collection"}).toArray(function(err, names) {
                    test.equal(0, names.length);
      
                    // Verify that the new collection exists
                    db.listCollections({name:"simple_rename_collection_2"}).toArray(function(err, names) {
                      test.equal(1, names.length);
      
                      db.close();
                    });
                  });
                });
              });
            });
          });
        });
      });
      // A simple example creating, dropping a collection and then verifying that the collection is gone.
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
        // Create a collection
        db.createCollection("simple_rename_collection_with_promise", {w:1}).then(function(collection) {
      
          // Insert a document in the collection
          collection.insertOne({a:1}, {w:1}).then(function(result) {
      
            // Retrieve the number of documents from the collection
            collection.count().then(function(count) {
              test.equal(1, count);
      
              // Rename the collection
              db.renameCollection("simple_rename_collection_with_promise", "simple_rename_collection_2_with_promise").then(function(collection2) {
      
                // Retrieve the number of documents from the collection
                collection2.count().then(function(count) {
                  test.equal(1, count);
      
                  // Verify that the collection is gone
                  db.listCollections({name:"simple_rename_collection_with_promise"}).toArray().then(function(names) {
                    test.equal(0, names.length);
      
                    // Verify that the new collection exists
                    db.listCollections({name:"simple_rename_collection_2_with_promise"}).toArray().then(function(names) {
                      test.equal(1, names.length);
      
                      db.close();
                    });
                  });
                });
              });
            });
          });
        });
      });
      // A simple example creating, dropping a collection and then verifying that the collection is gone.
      
      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 = yield db.createCollection("simple_rename_collection_with_generators", {w:1});
      
        // Insert a document in the collection
        yield collection.insertOne({a:1}, {w:1});
      
        // Retrieve the number of documents from the collection
        var count = yield collection.count();
        test.equal(1, count);
      
        // Rename the collection
        var collection2 = yield db.renameCollection("simple_rename_collection_with_generators", "simple_rename_collection_2_with_generators");
      
        // Retrieve the number of documents from the collection
        var count = yield collection2.count();
        test.equal(1, count);
      
        // Verify that the collection is gone
        var names = yield db.listCollections({name:"simple_rename_collection_with_generators"}).toArray();
        test.equal(0, names.length);
      
        // Verify that the new collection exists
        var names = yield db.listCollections({name:"simple_rename_collection_2_with_generators"}).toArray();
        test.equal(1, names.length);
      
        db.close();
      });

      stats(options, callback){Promise}

      Get all the db 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 Db~resultCallback optional

      The collection result callback

      Returns:
      Promise if no callback passed
      Examples
      // An example showing how to retrieve the db statistics
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
        test.equal(null, err);
      
        db.stats(function(err, stats) {
          test.equal(null, err);
          test.ok(stats != null);
      
          db.close();
        })
      });
      // An example showing how to retrieve the db statistics using a Promise.
      
      var MongoClient = require('mongodb').MongoClient,
        test = require('assert');
      MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
        db.stats().then(function(stats) {
          test.ok(stats != null);
      
          db.close();
        })
      });
      // An example showing how to retrieve the db 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');
        var stats = yield db.stats()
        test.ok(stats != null);
      
        db.close();
      });

      unref()

      Unref all sockets

      Type Definitions

      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.

      collectionsResultCallback(error, collections)

      The callback format for the collections method.

      Name Type Description
      error MongoError

      An error instance representing the error during the execution.

      collections Array.<Collection>

      An array of all the collections objects for the db instance.

      noResultCallback(error, result)

      The callback format for results

      Name Type Description
      error MongoError

      An error instance representing the error during the execution.

      result null

      Is not set to a value

      openCallback(error, db)

      The callback format for the Db.open method

      Name Type Description
      error MongoError

      An error instance representing the error during the execution.

      db Db

      The Db instance if the open method was successful.

      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.

      Events

      authenticated

      Db authenticated event

      Emitted after all server members in the topology (single server, replicaset or mongos) have successfully authenticated.

      Type:
      • object

      Db close event

      Emitted after a socket closed against a single server or mongos proxy.

      Type:

      Db error event

      Emitted after an error occurred against a single server or mongos proxy.

      Type:

      fullsetup

      Db fullsetup event, emitted when all servers in the topology have been connected to at start up time.

      • Server: Emitted when the driver has connected to the single server and has authenticated.
      • ReplSet: Emitted after the driver has attempted to connect to all replicaset members.
      • Mongos: Emitted after the driver has attempted to connect to all mongos proxies.
      Type:

      parseError

      Db parseError event

      The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server.

      Type:

      reconnect

      Db reconnect event

      • Server: Emitted when the driver has reconnected and re-authenticated.
      • ReplicaSet: N/A
      • Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos.
      Type:
      • object

      timeout

      Db timeout event

      Emitted after a socket timeout occurred against a single server or mongos proxy.

      Type:
      comments powered by Disqus