Get Started with the C++ Driver (original) (raw)

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.

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_STANDARDconfiguration option to your C++ version. Then, the driver will automatically use bsoncxx library polyfill implementations for required C++17 features.

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.1.4/mongo-cxx-driver-r4.1.4.tar.gz

tar -xzf mongo-cxx-driver-r4.1.4.tar.gz

cd mongo-cxx-driver-r4.1.4/build

Select the tab corresponding to your operating system and run following command from yourmongo-cxx-driver-r4.1.4/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-driverdirectory. Replace the following placeholder values:

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 Release

cmake --build . --config Debug

cmake --install . --config Release

cmake --install . --config Debug

Note

Windows Build Configurations

To avoid Windows linker errors due to conflicting build configurations, the preceding commands build and install both the Release and Debugconfigurations. To learn more about these configurations, see Shared Libraries (MSVC Only)in the API and ABI Versioning guide.

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.

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

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 aconnection 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 theChoose a Connection Target guide.

To retrieve your connection string for the deployment that you created in the previous step, log into your Atlas account and navigate to the Clusterspage under the Database section. Click the Connectbutton for your new deployment.

The connect button in the clusters section of the Atlas UI

If you do not already have a database user configured, MongoDB will prompt you to create and configure a new user.

Click the Drivers button underConnect to your application section and select "C++" from the Driver selection menu and the version that best matches the version you installed from the Versionselection menu.

Ensure the View full code sample option is deselected to view only the connection string.

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

Paste this connection string into a file in your preferred text editor and replace the <db_password> placeholder with your database user's password. The connection string is already populated with your database user's username.

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.

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

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


cd cpp-quickstart

touch quickstart.cpp

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")));

    if (result) {

        std::cout << bsoncxx::to_json(*result) << std::endl;

    } else {

        std::cout << "No result found" << std::endl;

    }

}

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

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 if your application prints "No result found", ensure that you specified the proper connection string in the quickstart.cppfile 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.

Congratulations on completing the quick start tutorial!

Note

If you run into issues in this tutorial, ask for help in the MongoDBStack Overflow pageor in the MongoDB Reddit community, or submit feedback by using the Rate this pagetab 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: