From driver version 1.2 we introduced a new connection Class that has the same name across all of our official drivers. This is to ensure that we present a recognizable front for all our API’s. This does not mean that your existing application will break, but rather that we encourage you to use the new connection api to simplify your application development.
Furthermore, the new connection class MongoClient acknowledges all writes to MongoDB, in contrast to the existing connection class Db that has acknowledgements turned off. Let’s take a tour of the MongoClient functions.
MongoClient = function(server, options);
MongoClient.prototype.open
MongoClient.prototype.close
MongoClient.prototype.db
MongoClient.connect
Outlined above is the complete MongoClient interface. The methods open, close and db work very similar to the existing methods on the Db class. The main difference is that the constructor is missing the database name from Db. Let’s show a simple connection using open as a code example speaks a thousand words.
var MongoClient = require('mongodb').MongoClient
, Server = require('mongodb').Server;
var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) {
var db1 = mongoClient.db("mydb");
mongoClient.close();
});
Notice that you configure the MongoClient just as you would have done the Db object. The main difference is that you access the db instances using the db method on the MongoClient object instead of using the Db instance directly as you would previously. MongoClient supports the same options as the previous Db instance you would have created.
So, with a minimal change in our app, we can apply the new MongoClient connection code. But there is more and one direction you might consider int the future. That is the mongodb connection string.
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
The URL format is unified across official drivers from 10gen with some options not supported on some drivers due to natural reasons. The ones not supported by the Node.js driver are left out for simplicities sake.
More detailed information about write concerns can be found at http://www.mongodb.org/display/DOCS/getLastError+Command
The url format can be used with MongoClient.connect. Where possible MongoClient will pick the best possible default values for options but they can be overridden. This includes setting auto_reconnect to true and native_parser to true if it’s available. Below are some example on how to connect to a single server a replicaset and a sharded system using MongoClient.connect
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:27017/integration_test", function(err, db) {
test.equal(null, err);
test.ok(db != null);
db.collection("replicaset_mongo_client_collection").update({a:1}, {b:1}, {upsert:true}, function(err, result) {
test.equal(null, err);
test.equal(1, result);
db.close();
test.done();
});
});
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:30000,localhost:30001/integration_test_?w=0&readPreference=secondary", function(err, db) {
test.equal(null, err);
test.ok(db != null);
db.collection("replicaset_mongo_client_collection").update({a:1}, {b:1}, {upsert:true}, function(err, result) {
test.equal(null, err);
test.equal(1, result);
db.close();
test.done();
});
});
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:50000,localhost:50001/integration_test_?w=0&readPreference=secondary", function(err, db) {
test.equal(null, err);
test.ok(db != null);
db.collection("replicaset_mongo_client_collection").update({a:1}, {b:1}, {upsert:true}, function(err, result) {
test.equal(null, err);
test.equal(1, result);
db.close();
test.done();
});
});
Notice that when connecting to the sharded system it’s pretty much the same url as for connecting to the replicaset. This is because the driver itself figures out if it’s a replicaset or a set of Mongos proxies it’s connecting to. No special care is needed to specify if it’s one or the other. This is in contrast to having to use the ReplSet or Mongos instances when using the open command.
A Connection Pool is a cache of database connections maintained by the driver so that connections can be re-used when new connections to the database are required. To reduce the number of connection pools created by your application, we recommend calling MongoClient.connect once and reusing the database variable returned by the callback:
var express = require('express');
var mongodb = require('mongodb');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var db;
// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/integration_test", function(err, database) {
if(err) throw err;
db = database;
// Start the application after the database connection is ready
app.listen(3000);
console.log("Listening on port 3000");
});
// Reuse database object in request handlers
app.get("/", function(req, res) {
db.collection("replicaset_mongo_client_collection").find({}, function(err, docs) {
docs.each(function(err, doc) {
if(doc) {
console.log(doc);
}
else {
res.end();
}
});
});
});
The connect function also takes a hash of options divided into db/server/replset/mongos allowing you to tweak options not directly supported by the unified url string format. To use these options you do pass in a hash like this:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:27017/integration_test_?", {
db: {
native_parser: false
},
server: {
socketOptions: {
connectTimeoutMS: 500
}
},
replSet: {},
mongos: {}
}, function(err, db) {
test.equal(null, err);
test.ok(db != null);
db.collection("replicaset_mongo_client_collection").update({a:1}, {b:1}, {upsert:true}, function(err, result) {
test.equal(null, err);
test.equal(1, result);
db.close();
test.done();
});
});
Below are all the options supported for db/server/replset/mongos.