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));
  db.open(function(err, db) {
    assert.equal(null, err);

    db.on('close', function() {
    })

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

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

    // Insert a document
    collection.insert({a:1}, configuration.writeConcernMax(), 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}, configuration.writeConcernMax(), function(err, result) {
          assert.ok(err != null);
          db.close();
        });
      });
    });
  });

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

listCollections

Get the list of all collection names for the specified db

Options
  • batchSize {Number, default:null}, The batchSize for the returned command cursor or if pre 2.8 the systems batch collection
listCollections(filter[, options][, options.batchSize=null])
Arguments:
  • filter (object) – Query to filter collections by
  • [options] (object) – additional options during update.
  • [options.batchSize=null] (number) – The batchSize for the returned command cursor or if pre 2.8 the systems batch collection
Returns:

cursor

Examples

An example of retrieving the collections list 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));
  db.open(function(err, db) {
    assert.equal(null, err);

    var db1 = db.db('listCollectionsTestDb');
    // Create a collection
    var collection = db1.collection('test_collections_info');
    collection.insert({a:1}, function(err, r) {
      assert.equal(null, err);

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

        // Return the information of a all collections, using the callback format
        db1.listCollections().toArray(function(err, items) {
          assert.equal(2, items.length);

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

An example of retrieving the collection names for a database using a filter

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) {
    assert.equal(null, err);

    // Create a collection
    var collection = db.collection('test_collections_info2');
    collection.insert({a:1}, function(err, r) {
      assert.equal(null, err);

      // Return the information of a single collection name
      db.listCollections({
          name: /test_collections_info2/
        }).toArray(function(err, items) {
        assert.ok(items.length >= 1);

        // Return the information of a all collections, using the callback format
        db.listCollections().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

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));
  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));
  db.open(function(err, db) {
    assert.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) {
      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));
  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], {readPreference: ReadPreference.PRIMARY}, function(err, result) {
        setTimeout(function() {
          // 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();
                          });
                        });
                      });
                    });
                  });
                });
              });
            });
          });
        }, 1000);
      });
    });
  });

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));
  db.open(function(err, db) {

    // Clean out the collection
    db.collection("system.js").remove({}, configuration.writeConcernMax(), 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; }")}, configuration.writeConcernMax(), 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

logout

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

Options
  • authMechanism {String, default:MONGODB-CR}, The authentication mechanism to use, GSSAPI or MONGODB-CR
  • authdb {String}, The Db to authenticate against instead of this
logout(callback[, options])
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.
  • [options] (object) – the options
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));
  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
  • authdb {String}, The Db to authenticate against instead of this
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));
  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);

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

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

      // Remove the user from the db
      db.removeUser('user', 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));
  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));
  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}, configuration.writeConcernMax(), 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));
  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));
  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}, configuration.writeConcernMax(), 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.listCollections({name:"a_simple_create_drop_collection"}).toArray(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));
  db.open(function(err, db) {
    assert.equal(null, err);

    // Create a collection
    db.createCollection("simple_rename_collection", configuration.writeConcernMax(), function(err, collection) {
      assert.equal(null, err);

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

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

          // 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.listCollections({name:"simple_rename_collection"}).toArray(function(err, names) {
                assert.equal(0, names.length);

                // Verify that the new collection exists
                db.listCollections({name:"simple_rename_collection_2"}).toArray(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.
  • 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));
  db.open(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.insert([{a:1, b:1}
      , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], configuration.writeConcernMax(), 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, 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 != 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.
  • 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));
  db.open(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.insert([{a:1, b:1}
      , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], configuration.writeConcernMax(), 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, 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 != 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

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

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.

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

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));
  db.open(function(err, db) {

    // Create a collection
    var collection = db.collection('more_index_information_test_1');
    // 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}], configuration.writeConcernMax(), 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));
  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

Contents

Manual

MongoDB Wiki