Working in MongoDB is as easy as working in our command-line tool in any operating system. While connecting a programming language like C++ via a Visual Studio tool to a database like MongoDB is not always simple as we do for other programming languages like Python and Java. Therefore, we are going to explain each step towards the connectivity of MongoDB using C++ in this guide. Before taking a look at the C++ code to connect with MongoDB, you need to install the required libraries and tools in the system. Starting from updating the system, we launch the console application and execut the “apt” instruction to update and upgrade the Linux system that we are currently working on which is the Ubuntu 22.04.
Install Prerequisites
The prerequisites that are required for the installation of MongoDB should be mounted via the console. The prerequisites include gnupg, apt-transport-https, ca-certificates, and common software properties. Using the same “apt” command, we install all of them at once.
The most important thing to do before the installation of MongoDB is to add its public key to our system. To do so, try out the following instruction in the shell and execute it. The “OK” return value shows its successful inclusion.
Warning: apt-key is deprecated. Manage keyring files in trusted.gpg.d instead (see apt-key(8)).
OK
After adding the key, we add the “apt” repository for MongoDB to the “sources.list.d” folder. After this, make sure to update your system once more.
deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse
Install MongoDB
We install the MongoDB meta-package right after all the prerequisites are installed. So, it’s time for its installation using the terminal. The command for its installation shows the use of the “mongodb-org” keyword with the “apt-get” utility of Linux, making it possible to install.
Restart and enable the mongodb service using the “systemctl” instruction of Linux. You will see that the MongoDB database server would be actively running as per the “status” instruction.
saeedraza@virtualbox:~$ sudo systemctl start mongod
saeedraza@virtualbox:~$ sudo systemctl status mongod
Another way to check if the MongoDB is active and running is to use the “—eval” flag with the “mongo” keyword followed by the “runCommand()” function. This function utilizes the ConnectionStatus argument as “1”. The “ok: 1” output shows that the MongoDB is active and running. If the status shows “0”, it means that the MongoDB is not yet active.
MongoDB shell version v5.0.14
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("71bf84e6-8b13-497a-b408-5e9283d0c016") }
MongoDB server version: 5.0.14
{
"authInfo" : {
"authenticatedUsers" : [ ],
"authenticatedUserRoles" : [ ]
},
"ok" : 1
}
To launch the MongoDB server, use the mongosh instruction on the terminal and you get the version of the MongoDB server and shell along with the initiated shell.
Current Mongosh Log ID: 63ac7e4a7d67f35e4f2d95b0
Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.1
Using MongoDB: 5.0.14
Using Mongosh: 1.6.1
When you run the “show dbs” instruction in the MongoDB shell, the built-in databases is displayed. Right now, we are working on the “Test” database.
admin 40.00 KiB
config 36.00 KiB
local 72.00 KiB
Let’s suppose you have a “Mongo” collection in the “test” database with some records in it.
Mongo
test> db.Mongo.find({})
[
{
_id: ObjectId("63ab69ea3e19b595a8fb0b90"),
Employee: { Name: 'Aina', Job: 'Police' }
}
]
Install Dependencies
The “libmongoc” library is a must-have to connect the MongoDB with C++ in Linux. Therefore, you have to install it using the “apt” install instruction within the console application.
There is a need for the “libbson” library to be used for connection so that we can add the “BSON” data into the database. The same style of apt-get instruction is used for its installation.
To create an “SSL” connection, the libssl-dev package library should be installed along with the SASL2 library, “libsasl2-dev”. The use of the “cmake” package is a must to connect C++ with MongoDB. Without using it, our program will not work.
Download and Install the C++ Driver for MongoDB
After installing the dependencies, it’s time to install the C++ driver for MongoDB in the Linux system. Go to the github’s official page for this driver’s “tar” file and download it at your end. You can also download it using the “curl” tool at the terminal. Moving within the currently utilized folder via the “ls” instruction of Linux, we list all the files and folders. The highlighted file in “Red” actually represents the “Mongodb-C++-driver” tar file.
saeedraza@virtualbox:~$ ls
a.out Downloads Music Public test.cpp
Desktop mongo-cxx-driver-r3.7.0 new.txt snap Videos
Documents mongo-cxx-driver-r3.7.0.tar.gz Pictures Templates
We need to run the “cmake” instruction to disable the automatic cleanup.
saeedraza@virtualbox:~/mongo-cxx-driver-r3.7.0$ cmake -DENABLE_AUTOMATIC-INIT_AND_CLEARNUP=OFF
Build the mongocxx driver within the same directory using the “—build” flag.
To install the built driver, run the following instruction:
Example of C++ Code
Starting from the C++ code example to elaborate on the connectivity of MongoDB with C++, we use the Visual Studio Code in our system. Create a C++ file where you have to build the mongocxx driver and run the code. The code starts with the use of basic libraries of “C++” along with the inclusion of mogocxx build files that are held in the driver folder after a build. All the required file paths are included as headers.
After this, we start our main() function to start the connectivity. The MongoDB instance is made and we declare the client address path as “URI” which is needed for the connection between C++ and MongoDB. A document stream is made as “doc”. The “try-catch” statement is utilized to run the important task to do and display the error in connection if there is any. The try statement declares a client using the “Uri” variable in the “con” variable. The “test” database is used in the “con” variable and the “Mongo” collection is called from the “test” database.
A document variable is generated and the “for” loop is here to get 2 variable values, “Name” and “job”, from the “Mongo” collection using the “BSON” format. Both records are displayed as a document. The catch() statement is here to run in case the connection didn’t get established.
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/client_session.hpp>
#include <mongocxx/stdx.hpp>
#include <mongocxx/uri.hpp>
#include <mongocxx/instance.hpp>
#include <bsoncxx/builder/stream/helpers.hpp>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/builder/stream/array.hpp>
using bsoncxx::builder::stream::close_array;
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::finalize;
using bsoncxx::builder::stream::open_array;
using bsoncxx::builder::stream::open_document;
int main(int argc, char* argv) {
mongocxx::instance inst{};
mongocxx::uri Uri("mongodb://localhost:27017");
bsoncxx::build::stream::document doc;
try {
mongocxx::client con(Uri);
mongocxx::database db = con("test")
mongocxx::collection col = db["Mongo"];
doc << "job" << argv[1];
mongocxx::cursor cur = col.find(doc.view());
for (auto&& d : cur) {
bsoncxx::document::element Name = d["name"];
bsoncxx::document::element Job = d["job"];
std::string strName = std::string(Name.get_utf8().value);
std::string strJob = std::string(Job.get_utf8().value);
std::cout << "Employee: " << Name << " : "<< Job <<std::endl;
}
} catch(const std::exception& e) {
std::cout <<"Connection Faild!" << e.what() << std::endl;
return EXIT_FAILURE;
}
return 0;
}
After running this C++ code file, we can fetch the records of a Mongo collection from the test database as displayed in the following:
Conclusion
This guide is a bundle of necessary steps to take for the connectivity process of C++ with the MongoDB database server. Starting from the introduction, we explained the difference in connectivity between C++ and other languages with MongoDB. After installing the prerequisites, we discussed the method to install the MongoDB server along with some of its dependencies before the installation of the MongoDB C++ driver. In the end, the C++ program is used in the Visual Studio after building the mongocxx driver to connect with MongoDB.