Db()

Constructor

Create a new Db instance.

class Db()
Arguments:
  • databaseName (string) – name of the database.
  • serverConfig (object) – server config object.
  • [options] (object) – additional options for the collection.
Options
  • w, {Number/String, > -1 || ‘majority’ || tag name} the write concern for the operation where < 1 is no acknowledgement of write and w >= 1, w = ‘majority’ or tag acknowledges the write
  • wtimeout, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
  • fsync, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
  • j, (Boolean, default:false) write waits for journal sync before returning
  • readPreference {String}, the preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  • native_parser {Boolean, default:false}, use c++ bson parser.
  • forceServerObjectId {Boolean, default:false}, force server to create _id fields instead of client.
  • pkFactory {Object}, object overriding the basic ObjectID primary key generation.
  • serializeFunctions {Boolean, default:false}, serialize functions.
  • raw {Boolean, default:false}, perform operations using raw bson buffers.
  • recordQueryStats {Boolean, default:false}, record query statistics during execution.
  • retryMiliSeconds {Number, default:5000}, number of milliseconds between retries.
  • numberOfRetries {Number, default:5}, number of retries off connection.
  • logger {Object, default:null}, an object representing a logger that you want to use, needs to support functions debug, log, error ({error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}}).
  • slaveOk {Number, default:null}, force setting of SlaveOk flag on queries (only use when explicitly connecting to a secondary server).
  • promoteLongs {Boolean, default:true}, when deserializing a Long will fit it into a Number if it’s smaller than 53 bits
  • bufferMaxEntries {Number, default: -1}, 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

Constants

Constant Name Value Description
Db.DEFAULT_URL ‘mongodb://localhost:27017/default’ Default URL

open

Initialize the database connection.

open(callback)
Arguments:
  • callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the index information or null if an error occurred.
Returns:

null

Examples

An example of a simple single server db connection

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {
  assert.equal(null, err);

  db.on('close', test.done.bind(test));
  db.close();
});

Simple replicaset connection setup, requires a running replicaset on the correct ports

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var replSet = new ReplSetServers([
  new Server('localhost', 30000),
  new Server('localhost', 30001),
  new Server('localhost', 30002)
]);
var db = new Db('integration_test_', replSet, {w:0});
db.open(function(err, p_db) {
  assert.equal(null, err);
  p_db.close();
});

Example of Read Preference usage at the query level.

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var replSet = new ReplSetServers([
  new Server('localhost', 30000),
  new Server('localhost', 30001),
  new Server('localhost', 30002)
]);
// Create db instance
var db = new Db('integration_test_', replSet, {w:0, native_parser: (process.env['TEST_NATIVE'] != null)});
// Trigger test once whole set is up
db.on("fullsetup", function() {
  // Rip out secondaries forcing an attempt to read from the primary
  db.serverConfig._state.secondaries = {};

  // Grab the collection
  db.collection("read_preference_replicaset_test_0", function(err, collection) {
    // Attempt to read (should fail due to the server not being a primary);
    collection.find().setReadPreference(ReadPreference.SECONDARY).toArray(function(err, items) {
      assert.ok(err != null);
      assert.equal("No replica set secondary available for query with ReadPreference SECONDARY", err.message);
      // Does not get called or we don't care
      db.close();
    });
  });
});

// Connect to the db
db.open(function(err, p_db) {
  db = p_db;
});

A Simple example off connecting to Mongos with a list of alternative proxies.

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

// Set up mongos connection
var mongos = new Mongos([
    new Server("localhost", 50000, { auto_reconnect: true }),
    new Server("localhost", 50001, { auto_reconnect: true })
  ])

// Connect using the mongos connections
var db = new Db('integration_test_', mongos, {w:0});
db.open(function(err, db) {
  assert.equal(null, err);
  assert.ok(db != null);

  // Perform a simple insert into a collection
  var collection = db.collection("shard_test");
  // Insert a simple doc
  collection.insert({test:1}, {w:1}, function(err, result) {
    assert.equal(null, err);

    collection.findOne({test:1}, {}, {readPreference:new ReadPreference(ReadPreference.SECONDARY)}, function(err, item) {
      assert.equal(null, err);
      assert.equal(1, item.test);

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

db

Create a new Db instance sharing the current socket connections.

db(dbName)
Arguments:
  • dbName (string) – the name of the database we want to use.
Returns:

db a db instance using the new database.

Examples

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

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {
  assert.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.insert({a:1}, {w:1}, function(err, result) {
    multipleColl2.insert({a:1}, {w:1}, function(err, result) {

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

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

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

close

Close the current db connection, including all the child db instances. Emits close event and calls optional callback.

close([forceClose], callback)
Arguments:
  • [forceClose] (boolean) – connection can never be reused.
  • callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results or null if an error occurred.
Returns:

null

Examples

An example that shows how to force close a db connection so it cannot be reused.

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {

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

  // Insert a document
  collection.insert({a:1}, {w:1}, function(err, result) {
    assert.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.insert({a:2}, {w:1}, function(err, result) {
        assert.equal('db closed by application', err.message);
      });
    });
  });
});

An example of a simple single server db connection and close function

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {
  assert.equal(null, err);

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

  });
});

admin

Access the Admin database

admin([callback])
Arguments:
  • [callback] (function) – returns the results.
Returns:

admin the admin db object.

Examples

Example showing how to access the Admin database for admin level operations.

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
db.open(function(err, db) {

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

  db.close();
});

collectionsInfo

Returns a cursor to all the collection information.

collectionsInfo([collectionName], callback)
Arguments:
  • [collectionName] (string) – the collection name we wish to retrieve the information from.
  • callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the options or null if an error occurred.
Returns:

null

Examples

An example of retrieving the information of all the collections.

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {
  assert.equal(null, err);

  // Create a collection
  db.createCollection('test_collections_info', function(err, r) {
    assert.equal(null, err);

    // Return the information of a single collection name
    db.collectionsInfo("test_collections_info").toArray(function(err, items) {
      assert.equal(1, items.length);

      // Return the information of a all collections, using the callback format
      db.collectionsInfo(function(err, cursor) {

        // Turn the cursor into an array of results
        cursor.toArray(function(err, items) {
          assert.ok(items.length > 0);

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

collectionNames

Get the list of all collection names for the specified db

Options
  • namesOnly {String, default:false}, Return only the full collection namespace.
collectionNames([collectionName][, options], callback)
Arguments:
  • [collectionName] (string) – the collection name we wish to filter by.
  • [options] (object) – additional options during update.
  • callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the collection names or null if an error occurred.
Returns:

null

Examples

An example of retrieving the collection names for a database.

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {
  assert.equal(null, err);

  // Create a collection
  db.createCollection('test_collections_info', function(err, r) {
    assert.equal(null, err);

    // Return the information of a single collection name
    db.collectionNames("test_collections_info", function(err, items) {
      assert.equal(1, items.length);

      // Return the information of a all collections, using the callback format
      db.collectionNames(function(err, items) {
        assert.ok(items.length > 0);

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

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’);

Options
  • w, {Number/String, > -1 || ‘majority’ || tag name} the write concern for the operation where &lt; 1 is no acknowledgement of write and w >= 1, w = ‘majority’ or tag acknowledges the write
  • wtimeout, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
  • fsync, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
  • j, (Boolean, default:false) write waits for journal sync before returning
  • serializeFunctions {Boolean, default:false}, serialize functions on the document.
  • raw {Boolean, default:false}, perform all operations using raw bson objects.
  • pkFactory {Object}, object overriding the basic ObjectID primary key generation.
  • readPreference {String}, the preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  • strict, (Boolean, default:false) returns an error if the collection does not exist
collection(collectionName[, options], callback)
Arguments:
  • collectionName (string) – the collection name we wish to access.
  • [options] (object) – returns option results.
  • callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the collection or null if an error occurred.
Returns:

null

Examples

An example of retrieving a collection from a db using the collection function.

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {
  assert.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) {
    assert.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) {
      assert.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) {
          assert.equal(null, err);

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

collections

Fetch all collections for the current db.

collections(callback)
Arguments:
  • callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the collections or null if an error occurred.
Returns:

null

Examples

An example of retrieving all collections for a db as Collection objects

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {
  assert.equal(null, err);

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

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

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

eval

Evaluate javascript on the server

Options
  • nolock {Boolean, default:false}, Tell MongoDB not to block on the evaulation of the javascript.
eval(code[, parameters][, options], callback)
Arguments:
  • code (code) – javascript to execute on server.
  • [parameters] (object) – the parameters for the call.
  • [options] (object) – the options
  • callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from eval or null if an error occurred.
Returns:

null

Examples

A whole bunch of examples on how to use eval on the server.

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open(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) {
    assert.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) {
    assert.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], function(err, result) {
    // Locate the entry
    db.collection('test_eval', function(err, collection) {
      collection.findOne(function(err, item) {
        assert.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) {
    assert.equal(5, result); tests_done();
  });

  // Evaluate a function with no parameters passed in
  db.eval('function () {return 5;}', function(err, result) {
    assert.equal(5, result); tests_done();
  });

  // Evaluate a statement
  db.eval('2 + 3;', function(err, result) {
    assert.equal(5, result); tests_done();
  });

  // Evaluate a statement using the code object
  db.eval(new Code("2 + 3;"), function(err, result) {
    assert.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) {
    assert.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) {
    assert.equal(5, result); tests_done();
  });

  // Evaluate an illegal statement
  db.eval("5 ++ 5;", function(err, result) {
    assert.ok(err instanceof Error);
    assert.ok(err.message != null);
    tests_done();
    // Let's close the db
    // db.close();
    // test.done();
  });
});

Defining and calling a system level javascript function (NOT recommended, <a href=’http://www.mongodb.org/display/DOCS/Server-side+Code+Execution’>http://www.mongodb.org/display/DOCS/Server-side+Code+Execution</a>)

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {

  // Clean out the collection
  db.collection("system.js").remove({}, {w:1}, function(err, result) {
    assert.equal(null, err);

    // Define a system level function
    db.collection("system.js").insert({_id: "echo", value: new Code("function(x) { return x; }")}, {w:1}, function(err, result) {
      assert.equal(null, err);

      db.eval("echo(5)", function(err, result) {
        assert.equal(null, err);
        assert.equal(5, result);

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

dereference

Dereference a dbref, against a db

dereference(dbRef, callback)
Arguments:
  • dbRef (dbref) – db reference object we wish to resolve.
  • callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from dereference or null if an error occurred.
Returns:

null

Examples

An example of dereferencing values.

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {
  assert.equal(null, err);

  // Get a second db
  var secondDb = db.db('integration_tests_2');

  // Create a dereference example
  secondDb.createCollection('test_deref_examples', function(err, collection) {

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

      // Let's build a db reference and resolve it
      var dbRef = new DBRef('test_deref_examples', ids[0]._id, 'integration_tests_2');

      // Resolve it including a db resolve
      db.dereference(dbRef, function(err, item) {
        assert.equal(1, item.a);

        // Let's build a db reference and resolve it
        var dbRef = new DBRef('test_deref_examples', ids[0]._id);

        // Simple local resolve
        secondDb.dereference(dbRef, function(err, item) {
          assert.equal(1, item.a);

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

logout

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

logout(callback)
Arguments:
  • callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from logout or null if an error occurred.
Returns:

null

Examples

An example of using the logout command for the database.

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
  // Establish connection to db
  db.open(function(err, db) {
    assert.equal(null, err);

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

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

        // Logout the db
        db.logout(function(err, result) {
          assert.equal(true, result);

          // Remove the user
          db.removeUser('user3', function(err, result) {
            assert.equal(true, result);

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

authenticate

Authenticate a user against the server. authMechanism Options

  • authMechanism {String, default:MONGODB-CR}, The authentication mechanism to use, GSSAPI or MONGODB-CR
authenticate(username, password[, options], callback)
Arguments:
  • username (string) – username.
  • password (string) – password.
  • [options] (object) – the options
  • callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from authentication or null if an error occurred.
Returns:

null

Examples

An example of using the authenticate command.

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
  // Establish connection to db
  db.open(function(err, db) {
    assert.equal(null, err);

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

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

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

addUser

Add a user to the database.

Options
  • w, {Number/String, > -1 || ‘majority’ || tag name} the write concern for the operation where &lt; 1 is no acknowledgement of write and w >= 1, w = ‘majority’ or tag acknowledges the write
  • wtimeout, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
  • fsync, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
  • j, (Boolean, default:false) write waits for journal sync before returning
  • customData, (Object, default:{}) custom data associated with the user (only Mongodb 2.6 or higher)
  • roles, (Array, default:[]) roles associated with the created user (only Mongodb 2.6 or higher)
addUser(username, password[, options], callback)
Arguments:
  • username (string) – username.
  • password (string) – password.
  • [options] (object) – additional options during update.
  • callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from addUser or null if an error occurred.
Returns:

null

Examples

An example of adding a user to the database.

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
  // Establish connection to db
  db.open(function(err, db) {
    assert.equal(null, err);

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

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

removeUser

Remove a user from a database

Options
  • w, {Number/String, > -1 || ‘majority’ || tag name} the write concern for the operation where &lt; 1 is no acknowledgement of write and w >= 1, w = ‘majority’ or tag acknowledges the write
  • wtimeout, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
  • fsync, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
  • j, (Boolean, default:false) write waits for journal sync before returning
removeUser(username[, options], callback)
Arguments:
  • username (string) – username.
  • [options] (object) – additional options during update.
  • callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from removeUser or null if an error occurred.
Returns:

null

Examples

An example of dereferencing values.

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
  // Establish connection to db
  db.open(function(err, db) {
    assert.equal(null, err);

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

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

        // Logout the db
        db.logout(function(err, result) {
          assert.equal(true, result);

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

            // Authenticate
            db.authenticate('user', 'name', function(err, result) {
              assert.equal(false, result);

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

createCollection

Creates a collection on a server pre-allocating space, need to create f.ex capped collections.

Options
  • w, {Number/String, > -1 || ‘majority’ || tag name} the write concern for the operation where &lt; 1 is no acknowledgement of write and w >= 1, w = ‘majority’ or tag acknowledges the write
  • wtimeout, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
  • fsync, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
  • j, (Boolean, default:false) write waits for journal sync before returning
  • serializeFunctions {Boolean, default:false}, serialize functions on the document.
  • raw {Boolean, default:false}, perform all operations using raw bson objects.
  • pkFactory {Object}, object overriding the basic ObjectID primary key generation.
  • capped {Boolean, default:false}, create a capped collection.
  • size {Number}, the size of the capped collection in bytes.
  • max {Number}, the maximum number of documents in the capped collection.
  • autoIndexId {Boolean, default:true}, create an index on the _id field of the document, True by default on MongoDB 2.2 or higher off for version &lt; 2.2.
  • readPreference {String}, the preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  • strict, (Boolean, default:false) throws an error if collection already exists
createCollection(collectionName[, options], callback)
Arguments:
  • collectionName (string) – the collection name we wish to access.
  • [options] (object) – returns option results.
  • callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from createCollection or null if an error occurred.
Returns:

null

Examples

A simple example showing the creation of a collection.

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {
  assert.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) {
    assert.equal(null, err);

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

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

command

Execute a command hash against MongoDB. This lets you acess any commands not available through the api on the server.

Options
  • readPreference {String}, the preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  • maxTimeMS {Number}, number of milliseconds to wait before aborting the query.
  • ignoreCommandFilter {Boolean}, overrides the default redirection of certain commands to primary.
  • writeCommand {Boolean, default: false}, signals this is a write command and to ignore read preferences
  • checkKeys {Boolean, default: false}, overrides the default not to check the key names for the command
command(selector[, options], callback)
Arguments:
  • selector (object) – the command hash to send to the server, ex: {ping:1}.
  • [options] (object) – additional options for the command.
  • callback (function) – this will be called after executing this method. The command always return the whole result of the command as the second parameter.
Returns:

null

Examples

A simple example creating, dropping a collection and then verifying that the collection is gone.

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {
  assert.equal(null, err);

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

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

dropCollection

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

dropCollection(collectionName, callback)
Arguments:
  • collectionName (string) – the name of the collection we wish to drop.
  • callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from dropCollection or null if an error occurred.
Returns:

null

Examples

A simple example executing a command against the server.

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {
  assert.equal(null, err);

  // Execute ping against the server
  db.command({ping:1}, function(err, result) {
    assert.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) {
      assert.equal(null, err);

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

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

          // Verify that the collection is gone
          db.collectionNames("a_simple_create_drop_collection", function(err, names) {
            assert.equal(0, names.length);

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

renameCollection

Rename a collection.

Options
  • dropTarget {Boolean, default:false}, drop the target name collection if it previously exists.
renameCollection(fromCollection, toCollection[, options], callback)
Arguments:
  • fromCollection (string) – the name of the current collection we wish to rename.
  • toCollection (string) – the new name of the collection.
  • [options] (object) – returns option results.
  • callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from renameCollection or null if an error occurred.
Returns:

null

Examples

A simple example creating, dropping a collection and then verifying that the collection is gone.

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {
  assert.equal(null, err);

  // Create a collection
  db.createCollection("simple_rename_collection", {w:1}, function(err, collection) {
    assert.equal(null, err);

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

      // Rename the collection
      db.renameCollection("simple_rename_collection", "simple_rename_collection_2", function(err, collection2) {
        assert.equal(null, err);

        // Retrieve the number of documents from the collection
        collection2.count(function(err, count) {
          assert.equal(1, count);

          // Verify that the collection is gone
          db.collectionNames("simple_rename_collection", function(err, names) {
            assert.equal(0, names.length);

            // Verify that the new collection exists
            db.collectionNames("simple_rename_collection_2", function(err, names) {
              assert.equal(1, names.length);

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

createIndex

Creates an index on the collection.

Options
  • w, {Number/String, > -1 || ‘majority’ || tag name} the write concern for the operation where &lt; 1 is no acknowledgement of write and w >= 1, w = ‘majority’ or tag acknowledges the write
  • wtimeout, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
  • fsync, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
  • j, (Boolean, default:false) write waits for journal sync before returning
  • unique {Boolean, default:false}, creates an unique index.
  • sparse {Boolean, default:false}, creates a sparse index.
  • background {Boolean, default:false}, creates the index in the background, yielding whenever possible.
  • dropDups {Boolean, default:false}, 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}, for geospatial indexes set the lower bound for the co-ordinates.
  • max {Number}, for geospatial indexes set the high bound for the co-ordinates.
  • v {Number}, specify the format version of the indexes.
  • expireAfterSeconds {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
  • name {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
createIndex(collectionName, fieldOrSpec[, options], callback)
Arguments:
  • collectionName (string) – name of the collection to create the index on.
  • fieldOrSpec (object) – fieldOrSpec that defines the index.
  • [options] (object) – additional options during update.
  • callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from createIndex or null if an error occurred.
Returns:

null

Examples

A more complex createIndex using a compound unique index in the background and dropping duplicated documents

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {

  // Create a collection we want to drop later
  db.createCollection('more_complex_index_test', function(err, collection) {
    assert.equal(null, err);

    // Insert a bunch of documents for the index
    collection.insert([{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) {
      assert.equal(null, err);

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

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

          // Peform a query, with explain to show we hit the query
          collection.find({a:2}, {explain:true}).toArray(function(err, explanation) {
            assert.equal(null, err);
            assert.ok(explanation[0].indexBounds.a != null);
            assert.ok(explanation[0].indexBounds.b != null);

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

ensureIndex

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

Options
  • w, {Number/String, > -1 || ‘majority’ || tag name} the write concern for the operation where &lt; 1 is no acknowledgement of write and w >= 1, w = ‘majority’ or tag acknowledges the write
  • wtimeout, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
  • fsync, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
  • j, (Boolean, default:false) write waits for journal sync before returning
  • unique {Boolean, default:false}, creates an unique index.
  • sparse {Boolean, default:false}, creates a sparse index.
  • background {Boolean, default:false}, creates the index in the background, yielding whenever possible.
  • dropDups {Boolean, default:false}, 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}, for geospatial indexes set the lower bound for the co-ordinates.
  • max {Number}, for geospatial indexes set the high bound for the co-ordinates.
  • v {Number}, specify the format version of the indexes.
  • expireAfterSeconds {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
  • name {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
ensureIndex(collectionName, fieldOrSpec[, options], callback)
Arguments:
  • collectionName (string) – name of the collection to create the index on.
  • fieldOrSpec (object) – fieldOrSpec that defines the index.
  • [options] (object) – additional options during update.
  • callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from ensureIndex or null if an error occurred.
Returns:

null

Examples

A more complex ensureIndex using a compound unique index in the background and dropping duplicated documents.

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {

  // Create a collection we want to drop later
  db.createCollection('more_complex_ensure_index_db_test', function(err, collection) {
    assert.equal(null, err);

    // Insert a bunch of documents for the index
    collection.insert([{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) {
      assert.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, dropDups:true, w:1}, function(err, indexName) {

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

          // Peform a query, with explain to show we hit the query
          collection.find({a:2}, {explain:true}).toArray(function(err, explanation) {
            assert.equal(null, err);
            assert.ok(explanation[0].indexBounds.a != null);
            assert.ok(explanation[0].indexBounds.b != null);

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

cursorInfo

Returns the information available on allocated cursors.

Options
  • readPreference {String}, the preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
cursorInfo([options], callback)
Arguments:
  • [options] (object) – additional options during update.
  • callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from cursorInfo or null if an error occurred.
Returns:

null

Examples

A Simple example of returning current cursor information in MongoDB

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {

  // Create a collection we want to drop later
  db.createCollection('cursor_information_collection', function(err, collection) {
    assert.equal(null, err);

    // Create a bunch of documents so we can force the creation of a cursor
    var docs = [];
    for(var i = 0; i < 1000; i++) {
      docs.push({a:'hello world hello world hello world hello world hello world hello world hello world hello world'});
    }

    // Insert a bunch of documents for the index
    collection.insert(docs, {w:1}, function(err, result) {
      assert.equal(null, err);

      // Let's set a cursor
      var cursor = collection.find({}, {batchSize:10});
      cursor.nextObject(function(err, item) {
        assert.equal(null, err);

        // Let's grab the information about the cursors on the database
        db.cursorInfo(function(err, cursorInformation) {
          assert.ok(cursorInformation.totalOpen > 0);

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

dropIndex

Drop an index on a collection.

dropIndex(collectionName, indexName, callback)
Arguments:
  • collectionName (string) – the name of the collection where the command will drop an index.
  • indexName (string) – name of the index to drop.
  • callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from dropIndex or null if an error occurred.
Returns:

null

Examples

An examples showing the creation and dropping of an index

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {

  // Create a collection we want to drop later
  db.createCollection('create_and_drop_an_index', function(err, collection) {
    assert.equal(null, err);

    // Insert a bunch of documents for the index
    collection.insert([{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) {
      assert.equal(null, err);

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

        // Drop the index
        db.dropIndex("create_and_drop_an_index", "a_1_b_1", function(err, result) {
          assert.equal(null, err);

          // Verify that the index is gone
          collection.indexInformation(function(err, indexInformation) {
            assert.deepEqual([ [ '_id', 1 ] ], indexInformation._id_);
            assert.equal(null, indexInformation.a_1_b_1);

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

reIndex

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.

reIndex(collectionName, callback)
Arguments:
  • collectionName (string) – the name of the collection.
  • callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from reIndex or null if an error occurred.

Examples

An example showing how to force a reindex of a collection.

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {

  // Create a collection we want to drop later
  db.createCollection('create_and_drop_all_indexes', function(err, collection) {
    assert.equal(null, err);

    // Insert a bunch of documents for the index
    collection.insert([{a:1, b:1}, {a:1, b:1}
      , {a:2, b:2}, {a:3, b:3}, {a:4, b:4, c:4}], {w:1}, function(err, result) {
      assert.equal(null, err);

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

        // Force a reindex of the collection
        db.reIndex('create_and_drop_all_indexes', function(err, result) {
          assert.equal(null, err);
          assert.equal(true, result);

          // Verify that the index is gone
          collection.indexInformation(function(err, indexInformation) {
            assert.deepEqual([ [ '_id', 1 ] ], indexInformation._id_);
            assert.deepEqual([ [ 'a', 1 ], [ 'b', 1 ] ], indexInformation.a_1_b_1);

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

indexInformation

Retrieves this collections index info.

Options
  • full {Boolean, default:false}, returns the full raw index information.
  • readPreference {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST).
indexInformation(collectionName[, options], callback)
Arguments:
  • collectionName (string) – the name of the collection.
  • [options] (object) – additional options during update.
  • callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from indexInformation or null if an error occurred.
Returns:

null

Examples

An example showing the information returned by indexInformation

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {

  // Create a collection we want to drop later
  db.createCollection('more_index_information_test', function(err, collection) {
    assert.equal(null, err);

    // Insert a bunch of documents for the index
    collection.insert([{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) {
      assert.equal(null, err);

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

        // Fetch basic indexInformation for collection
        db.indexInformation('more_index_information_test', function(err, indexInformation) {
          assert.deepEqual([ [ '_id', 1 ] ], indexInformation._id_);
          assert.deepEqual([ [ 'a', 1 ], [ 'b', 1 ] ], indexInformation.a_1_b_1);

          // Fetch full index information
          collection.indexInformation({full:true}, function(err, indexInformation) {
            assert.deepEqual({ _id: 1 }, indexInformation[0].key);
            assert.deepEqual({ a: 1, b: 1 }, indexInformation[1].key);

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

dropDatabase

Drop a database.

dropDatabase(callback)
Arguments:
  • callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from dropDatabase or null if an error occurred.
Returns:

null

Examples

An examples showing the dropping of a database

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {

  // Create a collection
  db.createCollection('more_index_information_test', function(err, collection) {
    assert.equal(null, err);

    // Insert a bunch of documents for the index
    collection.insert([{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) {
      assert.equal(null, err);

      // Let's drop the database
      db.dropDatabase(function(err, result) {
        assert.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) assert.equal(false, found);

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

stats

Get all the db statistics.

Options
  • scale {Number}, divide the returned sizes by scale value.
  • readPreference {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST).
stats([options], callback)
Arguments:
  • [options] (objects) – options for the stats command
  • callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from stats or null if an error occurred.
Returns:

null

Examples

An example showing how to retrieve the db statistics

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {
  assert.equal(null, err);

  db.stats(function(err, stats) {
    assert.equal(null, err);
    assert.ok(stats != null);

    db.close();
  })
});

Db.connect

Connect to MongoDB using a url as documented at

docs.mongodb.org/manual/reference/connection-string/

Options
  • uri_decode_auth {Boolean, default:false} uri decode the user name and password for authentication
  • db {Object, default: null} a hash off options to set on the db object, see Db constructor
  • server {Object, default: null} a hash off options to set on the server objects, see Server constructor**
  • replSet {Object, default: null} a hash off options to set on the replSet object, see ReplSet constructor**
  • mongos {Object, default: null} a hash off options to set on the mongos object, see Mongos constructor**
Db.connect(url[, options], callback)
Arguments:
  • url (string) – connection url for MongoDB.
  • [options] (object) – optional options for insert command
  • callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the db instance or null if an error occurred.
Returns:

null

Examples

Example of a simple url connection string, with no acknowledgement of writes.

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

// Connect to the server
Db.connect(configuration.url(), function(err, db) {
  assert.equal(null, err);

  db.close();
});

Contents

Manual

MongoDB Wiki