MongoClient()

Constructor

Create a new MongoClient instance.

class MongoClient()
Arguments:
  • 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 acknowlegement 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 prefered 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}, peform operations using raw bson buffers.
  • recordQueryStats {Boolean, default:false}, record query statistics during execution.
  • retryMiliSeconds {Number, default:5000}, number of miliseconds between retries.
  • numberOfRetries {Number, default:5}, number of retries off connection.
  • bufferMaxEntries {Boolean, 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

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**
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 occured, or null otherwise. While the second parameter will contain the initialized db object or null if an error occured.
Returns:

null

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 occured, or null otherwise. While the second parameter will contain the connected mongoclient or null if an error occured.
Returns:

null

Examples

A basic example using the MongoClient to connect using a Server instance, similar to existing Db version

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 the connection to the local db
  var mongoclient = new MongoClient(new Server("localhost", 27017), {native_parser: true});

  // Open the connection to the server
  mongoclient.open(function(err, mongoclient) {

    // Get the first db and do an update document on it
    var db = mongoclient.db("integration_tests");
    db.collection('mongoclient_test').update({a:1}, {b:1}, {upsert:true}, function(err, result) {
      assert.equal(null, err);
      assert.equal(1, result);

      // Get another db and do an update document on it
      var db2 = mongoclient.db("integration_tests2");
      db2.collection('mongoclient_test').update({a:1}, {b:1}, {upsert:true}, function(err, result) {
        assert.equal(null, err);
        assert.equal(1, result);

        // Close the connection
        mongoclient.close();
      });
    });
  });

close

Close the current db connection, including all the child db instances. Emits close event if no callback is provided.

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

null

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.

MongoClient.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**
MongoClient.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 occured, or null otherwise. While the second parameter will contain the initialized db object or null if an error occured.
Returns:

null

Examples

Example of a simple url connection string for a single server 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');

  // Connect using the connection string
  MongoClient.connect("mongodb://localhost:27017/integration_tests", {native_parser:true}, function(err, db) {
    assert.equal(null, err);

    db.collection('mongoclient_test').update({a:1}, {b:1}, {upsert:true}, function(err, result) {
      assert.equal(null, err);
      assert.equal(1, result);

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

Example of a simple url connection string to a replicaset, with 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');

MongoClient.connect("mongodb://localhost:30000,localhost:30001,localhost:30002/integration_test_?w=1", function(err, db) {
  assert.equal(null, err);
  assert.ok(db != null);

  db.collection("replicaset_mongo_client_collection").update({a:1}, {b:1}, {upsert:true}, function(err, result) {
    assert.equal(null, err);
    assert.equal(1, result);

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

Example of a simple url connection string to a shard, with 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');

MongoClient.connect('mongodb://localhost:50000,localhost:50001/sharded_test_db?w=1', function(err, db) {
  assert.equal(null, err);
  assert.ok(db != null);

  db.collection("replicaset_mongo_client_collection").update({a:1}, {b:1}, {upsert:true}, function(err, result) {
    assert.equal(null, err);
    assert.equal(1, result);

    process.exit(0)
    db.close();
  });
});

Contents

Manual

MongoDB Wiki