Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping open a MongoDB database connection

In so many introductory examples of using MongoDB, you see code like this:

var MongoClient = require('mongodb').MongoClient; MongoClient.connect("mongodb://localhost:port/adatabase", function(err, db) {     /* Some operation... CRUD, etc. */     db.close(); }); 

If MongoDB is like any other database system, open and close operations are typically expensive time-wise.

So, my question is this: Is it OK to simply do the MongoClient.connect("... once, assign the returned db value to some module global, have various functions in the module do various database-related work (insert documents into collections, update documents, etc. etc.) when they're called by other parts of the application (and thereby re-use that db value), and then, when the application is done, only then do the close.

In other words, open and close are done once - not every time you need to go and do some database-related operation. And you keep re-using that db object that was returned during the initial open\connect, only to dispose of it at the end, with the close, when you're actually done with all your database-related work.

Obviously, since all the I/O is asynch, before the close you'd make sure that the last database operation completed before issuing the close. Seems like this should be OK, but i wanted to double-check just in case I'm missing something as I'm new to MongoDB. Thanks!

like image 308
Lew Avatar asked Sep 06 '13 05:09

Lew


People also ask

Does MongoDB close connection automatically?

1.3 close() method in the Mongo databaseThe server will automatically close the cursors that have no remaining results and the cursors that have been idle for a time. Here is what the query syntax will look like.

How do I know if MongoDB is connected?

isConnected runs getDbObject . getDbObject connects to mongoDB and returns an object: connected (true/false), db (dbObject or error). Then, isConnected resolve/reject by connected property.

What is MongoDB connection pooling?

A connection pool is a cache of open, ready-to-use database connections maintained by the driver. Your application can seamlessly get connections from the pool, perform operations, and return connections back to the pool. Connection pools are thread-safe.


1 Answers

Yes, that is fine and typical behavior. start your app, connect to db, do operations against the db for a long time, maybe re-connect if the connection ever dies unexpectedly, and then just never close the connection (just rely on the automatic close that happens when your process dies).

like image 80
Peter Lyons Avatar answered Sep 25 '22 02:09

Peter Lyons