exebook
exebook

Reputation: 33980

Why connecting to MongoDB from Node.js is slow

Here is my "hello world" minimal Node.js application to connect to the database installed and running on the localhost. This small app take significant amount of time 0.41 seconds to be precise.

var mongo = require('mongodb').MongoClient
var c = mongo.connect('mongodb://localhost',
function(err, db){
    console.log(db)
    db.close()
})

At the same time, using MongoDB default shell that you can execute from the command line, called mongo, I could connect almsot ten times faster. And it even executes a simple command.

$ time mongo --eval "db"
MongoDB shell version: 2.4.6
connecting to: test
test

real    0m0.054s
user    0m0.045s
sys 0m0.008s

Why connecting from Node.js is slower, how to speed it up to achieve the same speed as the native shell connection speed?

Upvotes: 1

Views: 2155

Answers (1)

Kailan Blanks
Kailan Blanks

Reputation: 322

What you're timing here is the time it takes node to start, load the mongo module and only then connect. You'll find that most of this isn't connecting to the DB itself but rather parsing, loading and executing the entire script.

Try running the timing from inside of the script after the mongodb module has been loaded.

Upvotes: 1

Related Questions