Connect to MongoDB
Create a project directory
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
Create your C++ driver application
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; }
Assign the connection string
Replace the <connection string>
placeholder with the
connection string that you copied from the Create a Connection String
step of this guide.
Run your C++ application
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.
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.