C++ MongoDB

MongoDB Connection Pool in C++

I’ve found that there are only a few examples showing how to use MongoDB’s C++ client driver with a connection pool. Now for most applications a pool won’t be necessary, but in my case I needed to have multiple concurrent connections to a MongoDB server.

At the time of this writing there is one caveat when using the C++ driver’s connection pool that is worth mentioning: You can not use it with authenticated connections.

Basic example

Okay so assuming you won’t need authentication just yet, here is a snippet for using a connection pool:

That is rather simple and I believe it should have been added to the MongoDB documentation for the C++ driver by now.

Exception handling

I’ve found that the constructor of the ScopedDBConnection often throws an exception if something went wrong. To ensure safe handling of exceptions rather use this snippet:

That’s it. I don’t believe any more explanation is required as the comments and code is self-explanatory. The function may be called by multiple threads and the pool should manage itself.

Please let me know if you use connection pools with the C++ client driver.



By Pieter Jordaan

Pieter is a Ph.D student in computer and electronic engineering at the University of the North West. His field of study is a hybrid approach to relational and non-relational databases.

He also enjoys playing the guitar and singing songs. He is married to the beautiful co-author Jeanne-mari Jordaan

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.