ANNOUNCEMENT: Voyage AI joins MongoDB to power more accurate and trustworthy AI applications on Atlas.
Learn more
Docs Menu

Get Started with the C++ Driver

The MongoDB C++ Driver is a C++ package that you can use to connect to MongoDB and interact with data stored in your deployment. This guide shows you how to create an application that uses the C++ driver to connect to a MongoDB cluster hosted on MongoDB Atlas and query data in your cluster.

Tip

MongoDB Atlas is a fully managed cloud database service that hosts your MongoDB deployments. You can create your own free (no credit card required) MongoDB Atlas deployment by following the steps in this guide.

Follow this guide to connect a sample C++ application to a MongoDB Atlas deployment. If you prefer to connect to MongoDB using a different driver or programming language, see our list of official drivers.

1

Before you begin this tutorial, ensure you have the following dependencies installed in your development environment:

Note

Pre-C++17 Configurations

Although C++11 is the minimum supported language version, this tutorial configures the C++ driver to use the C++17 standard library as recommended by the C++17 Polyfill Configuration section. If you want to install the driver for pre-C++17 configurations, set the CMAKE_CXX_STANDARD configuration option to your C++ version. Then, the driver will automatically use bsoncxx library polyfill implementations for required C++17 features.

2

To download the latest version of the C++ driver from the mongo-cxx-driver Github repository, run the following commands in your shell from your root directory:

curl -OL https://github.com/mongodb/mongo-cxx-driver/releases/download/r4.0.0/mongo-cxx-driver-r4.0.0.tar.gz
tar -xzf mongo-cxx-driver-r4.0.0.tar.gz
cd mongo-cxx-driver-r4.0.0/build
3

Select the tab corresponding to your operating system and run following command from your mongo-cxx-driver-r4.0.0/build directory:

cmake .. \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_CXX_STANDARD=17

This command instructs CMake to install mongocxx into the /usr/local directory.

'C:\<path>\cmake.exe' .. \
-G "Visual Studio <version> <year>" -A "x64" \
-DCMAKE_CXX_STANDARD=17 \
-DCMAKE_INSTALL_PREFIX=C:\mongo-cxx-driver \

This command instructs CMake to install mongocxx into the C:\mongo-cxx-driver directory. Replace the following placeholder values:

  • <path>: The path to your CMake executable

  • <version>: Your Visual Studio version number

  • <year>: The year corresponding to your Visual Studio version

4

Select the tab corresponding to your operating system and run following commands to install the driver:

cmake --build .
sudo cmake --build . --target install
cmake --build . --config RelWithDebInfo
cmake --build . --target install --config RelWithDebInfo

After you complete these steps, you have the C++ driver installed on your machine.

You can create a free tier MongoDB deployment on MongoDB Atlas to store and manage your data. MongoDB Atlas hosts and manages your MongoDB database in the cloud.

1

Complete the Get Started with Atlas guide to set up a new Atlas account and load sample data into a new free tier MongoDB deployment.

2

After you create your database user, save that user's username and password to a safe location for use in an upcoming step.

After you complete these steps, you have a new free tier MongoDB deployment on Atlas, database user credentials, and sample data loaded into your database.

You can connect to your MongoDB deployment by providing a connection URI, also called a connection string, which instructs the driver on how to connect to a MongoDB deployment and how to behave while connected.

The connection string includes the hostname or IP address and port of your deployment, the authentication mechanism, user credentials when applicable, and connection options.

To connect to an instance or deployment not hosted on Atlas, see the Choose a Connection Target guide.

1

To retrieve your connection string for the deployment that you created in the previous step, log in to your Atlas account and navigate to the Database section and click the Connect button for your new deployment.

The connect button in the clusters section of the Atlas UI

Proceed to the Connect your application section and select "C++" from the Driver selection menu and the version that best matches the version you installed from the Version selection menu.

Select the Password (SCRAM) authentication mechanism.

Deselect the Include full driver code example option to view only the connection string.

2

Click the button on the right of the connection string to copy it to your clipboard, as shown in the following screenshot:

The copy button next to the connection string in the Atlas UI
3

Paste this connection string into a file in your preferred text editor and replace the <username> and <password> placeholders with your database user's username and password.

Save this file to a safe location for use in the next step.

After completing these steps, you have a connection string that corresponds to your Atlas cluster.

1

From your root directory, run the following command in your shell to create a directory called cpp-quickstart for this project:

mkdir cpp-quickstart

Run the following commands to create a quickstart.cpp application file in the cpp-quickstart directory:

cd cpp-quickstart
touch quickstart.cpp
2

Copy and paste the following code into the quickstart.cpp file, which queries the movies collection in the sample_mflix database:

#include <cstdint>
#include <iostream>
#include <vector>
#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;
int main() {
mongocxx::instance instance;
mongocxx::uri uri("<connection string>");
mongocxx::client client(uri);
auto db = client["sample_mflix"];
auto collection = db["movies"];
auto result = collection.find_one(make_document(kvp("title", "The Shawshank Redemption")));
std::cout << bsoncxx::to_json(*result) << std::endl;
}
3

Replace the <connection string> placeholder with the connection string that you copied from the Create a Connection String step of this guide.

4

In your shell, run the following commands to compile and run this application:

c++ --std=c++17 quickstart.cpp $(pkg-config --cflags --libs libmongocxx) -o ./app.out
./app.out

Tip

MacOS users might see the following error after running the preceding commands:

dyld[54430]: Library not loaded: @rpath/libmongocxx._noabi.dylib

To resolve this error, use the -Wl,-rpath linker option to set the @rpath, as shown in the following code:

c++ --std=c++17 quickstart.cpp -Wl,-rpath,/usr/local/lib/ $(pkg-config --cflags --libs libmongocxx) -o ./app.out
./app.out

The command line output contains details about the retrieved movie document:

{ "_id" : { "$oid" : "573a1399f29313caabceeb20" },
"plot" : "Two imprisoned men bond over a number of years, finding solace
and eventual redemption through acts of common decency.",
...
"title" : "The Shawshank Redemption",
...

If you encounter an error or see no output, ensure that you specified the proper connection string in the quickstart.cpp file and that you loaded the sample data.

After you complete these steps, you have a working application that uses the driver to connect to your MongoDB deployment, runs a query on the sample data, and prints out the result.

Next Steps

Congratulations on completing the quick start tutorial!

Note

If you run into issues on this step, ask for help in the MongoDB Community Forums or submit feedback by using the Rate this page tab on the right or bottom right side of this page.

In this tutorial, you created a C++ application that connects to a MongoDB deployment hosted on MongoDB Atlas and retrieves a document that matches a query.

Learn more about C++ driver from the following resources: