Skip to content

Instantly share code, notes, and snippets.

@brettkiefer
Created April 18, 2011 17:48
Show Gist options
  • Save brettkiefer/925784 to your computer and use it in GitHub Desktop.
Save brettkiefer/925784 to your computer and use it in GitHub Desktop.
Shows one case where parallel connections to MongoDB give a substantial speedup
// Modified from node-mongodb-native example
sys = require("sys");
var Db = require('mongodb').Db,
Connection = require('mongodb').Connection,
Server = require('mongodb').Server,
// BSON = require('mongodb').BSONPure;
BSON = require('mongodb').BSONNative;
var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost';
var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT;
sys.puts("Connecting to " + host + ":" + port);
var db1 = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true});
var db2 = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true});
function aString(length) {
var str = '';
for (var i = 0; i < length; i++) {
str += 'a';
}
return str;
}
var x = aString(1 * 1000 * 1000);
var dt = new Date();
var logTime = function(rg) {
rg.push((new Date).getTime() - dt.getTime());
sys.puts(rg);
};
logTime(["start"]);
var nFound = 0;
db1.open(function(err, db1) {
db2.open(function(err, db2) {
db1.collection('test', function(err, collection) {
logTime(["connected"]);
collection.remove(function(err, collection) {
logTime(["removed"]);
var fx = function(db, n) {
db.collection('test', function(err, collection) {
// Insert 3 records
for(var i = 0; i < 3; i++) {
collection.insert({'a':x}, function(err) {
logTime(["inserted", n]);
});
}
logTime(["about to find"]);
collection.find(function(err, cursor) {
cursor.each(function(err, item) {
logTime(["found", item, n, ++nFound]);
});
});
});
};
fx(db1, 1);
// Switch which of the following two lines is commented out to test the 1db vs. 2 db case
fx(db2, 2);
//fx(db1, 1);
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment