### Example Static Library Directory Structure (Unix-like) Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/reference/api-abi-versioning This example shows the expected shared and static library files for a bsoncxx library in a typical Unix-like installation directory. ```none ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}/ ├── libbsoncxx.so.1.2.3 ├── libbsoncxx.so.10 -> libbsoncxx.so.1.2.3 ├── libbsoncxx.so -> libbsoncxx.so.10 ├── libbsoncxx-static.a ├── cmake/bsoncxx-1.2.3/ │ ├── bsoncxx-config.cmake │ └── ... └── pkgconfig/ ├── libbsoncxx.pc └── libbsoncxx-static.pc ``` -------------------------------- ### Build and Install Driver Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/get-started Commands to compile and install the driver binaries. ```bash cmake --build . sudo cmake --build . --target install ``` ```bash cmake --build . --config Release cmake --build . --config Debug cmake --install . --config Release cmake --install . --config Debug ``` -------------------------------- ### Example Program Output Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/include-link Expected output when running the view_and_value example program. ```none { "team" : "platforms", "id" : { "$oid" : "66f4be6fef9eb8b9240619f0" }, "members" : [ "tyler", "jason", "drew", "sam", "ernie", "john", "mark", "crystal" ] } Got key, key = team Got String! Got key, key = id Got ObjectId! Got key, key = members Got Array! array element: tyler array element: jason array element: drew array element: sam array element: ernie array element: john array element: mark array element: crystal as expected, we have a team document has 3 keys. document keys are: team id members ``` -------------------------------- ### Library Real Name Examples Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/reference/api-abi-versioning Examples of expected shared library filenames. ```none libbsoncxx.so.1.0.0 libbsoncxx.so.2.3.4 ``` -------------------------------- ### Install Conan Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/advanced-installation Commands to install Conan and initialize the default profile. ```bash $ pip install conan $ conan profile detect --force ``` -------------------------------- ### Library Directory Layout Example Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/reference/api-abi-versioning Example of a library directory containing versioned files and symlinks for API version 1.2.3 and ABI version 10. ```none ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}/ ├── libbsoncxx.so.1.2.3 ├── libbsoncxx.so.10 -> libbsoncxx.so.1.2.3 ├── libbsoncxx.so -> libbsoncxx.so.10 ├── cmake/bsoncxx-1.2.3/ │ ├── bsoncxx-config.cmake │ └── ... └── pkgconfig/ └── libbsoncxx.pc ``` -------------------------------- ### Install Vcpkg Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/advanced-installation Commands to clone and bootstrap the Vcpkg package manager. ```bash $ git clone https://github.com/Microsoft/vcpkg.git $ cd vcpkg $ ./bootstrap-vcpkg.sh ``` -------------------------------- ### Example Output Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/crud/update/replace The expected JSON output after a successful document replacement. ```cli New document: { "_id" : { "$oid" : "..." }, "name" : "La Bernadin" } ``` -------------------------------- ### Install to a non-standard directory Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/advanced-installation Sets the installation prefix to a custom path. ```bash cmake .. \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_INSTALL_PREFIX=$HOME/mongo-cxx-driver ``` -------------------------------- ### Vector Search Index Creation Output Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/indexes/vector-search-index Example output after successfully creating a vector search index. ```cli New vector search index name: vector_search ``` -------------------------------- ### Example Query Output Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/indexes/compound-index Sample JSON output representing a document retrieved from the collection. ```cli { "_id" :..., "plot" : "Peter Pan enters the nursery of the Darling children...", ..., "year" : 1924, "imdb" : ..., "type", "movie",...} ``` -------------------------------- ### Example Execution Output Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/include-link Expected output after running the view_and_value executable. ```text { "team" : "platforms", "id" : { "$oid" : "67207dcf532837a4470cc090" }, "members" : [ "tyler", "jason", "drew", "sam", "ernie", "john", "mark", "crystal" ] } Got key, key = team Got String! Got key, key = id Got ObjectId! Got key, key = members Got Array! array element: tyler array element: jason array element: drew array element: sam array element: ernie array element: john array element: mark array element: crystal as expected, we have a team document has 3 keys. document keys are: team id members ``` -------------------------------- ### Example command line output Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/get-started Sample JSON output format returned by the application when querying a movie document. ```none { "_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", ... ``` -------------------------------- ### Configure CMake for Driver Installation Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/include-link Use this command to specify the C++ standard and installation prefix when the driver is in a non-standard location. ```none cmake -Bbuild -DCMAKE_CXX_STANDARD=17 -DCMAKE_PREFIX_PATH=/opt/mongodb/cxx-driver ``` -------------------------------- ### Install MongoDB C++ Driver via Vcpkg Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/advanced-installation Command to install the driver using the Vcpkg package manager. ```bash $ ./vcpkg install mongo-cxx-driver ``` -------------------------------- ### Insert Sample Data into a Collection Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/crud/query/specify-a-query Initializes the database and collection, then inserts multiple documents to be used for query examples. ```cpp mongocxx::uri uri(""); mongocxx::client client(uri); auto db = client["db"]; auto collection = db["fruits"]; std::vector fruits; fruits.push_back(make_document(kvp("_id", 1), kvp("name", "apples"), kvp("qty", 5), kvp("rating", 3), kvp("color", "red"), kvp("type", make_array("fuji", "honeycrisp")))); fruits.push_back(make_document(kvp("_id", 2), kvp("name", "bananas"), kvp("qty", 7), kvp("rating", 4), kvp("color", "yellow"), kvp("type", make_array("cavendish")))); fruits.push_back(make_document(kvp("_id", 3), kvp("name", "oranges"), kvp("qty", 6), kvp("rating", 2), kvp("type", make_array("naval", "mandarin")))); fruits.push_back(make_document(kvp("_id", 4), kvp("name", "pineapples"), kvp("qty", 3), kvp("rating", 5), kvp("color", "yellow"))); auto result = collection.insert_many(fruits); ``` -------------------------------- ### Configure and Build C++ Application with CMake Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/advanced-installation Use these commands to configure the build environment with the driver path and install the resulting binary. ```bash cmake \ -DCMAKE_PREFIX_PATH=$HOME/mongo-cxx-driver \ -DCMAKE_INSTALL_PREFIX=$HOME/app \ -DCMAKE_INSTALL_RPATH_USE_LINK_PATH=TRUE \ -DCMAKE_CXX_STANDARD=11 \ -Bcmake-build -S. cmake --build cmake-build --target install $HOME/app/bin/app.out ``` -------------------------------- ### Query a collection in C++ Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/get-started A complete example demonstrating how to connect to a database and perform a find_one operation. ```cpp #include #include #include #include #include #include #include #include using bsoncxx::builder::basic::kvp; using bsoncxx::builder::basic::make_document; int main() { mongocxx::instance instance; mongocxx::uri uri(""); 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; } } ``` -------------------------------- ### Start MongoDB for Integration Tests Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/reference/testing Command to launch a mongod instance with test commands enabled for integration testing. ```bash mongod --setParameter enableTestCommands=1 ``` ```bash ./mongod --setParameter enableTestCommands=1 ``` -------------------------------- ### Configure project with CMake Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/reference/api-abi-versioning Use the bsoncxx_ROOT variable to point CMake to the driver installation directory. ```bash cmake -S example -B example-build -D bsoncxx_ROOT="$INSTALLDIR" ``` -------------------------------- ### Example Explain Output Structure Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/aggregation This is a partial representation of the JSON output from the explain command, showing the 'explainVersion', 'queryPlanner', and 'winningPlan' sections. ```json { "explainVersion" : "2", "queryPlanner" : { "namespace" : "sample_restaurants.restaurants", "indexFilterSet" : false, "parsedQuery" : { "cuisine" : { "$eq" : "Bakery" } }, "queryHash": "...", "planCacheKey" : "...", "optimizedPipeline" : true, "maxIndexedOrSolutionsReached": false, "maxIndexedAndSolutionsReached" : false, "maxScansToExplodeReached" : false, "winningPlan" : { ... } ... } ``` -------------------------------- ### Compile with pkg-config Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/reference/api-abi-versioning Set PKG_CONFIG_PATH to the installation directory and use pkg-config to retrieve compiler and linker flags. ```bash bsoncxx_cflags="$(PKG_CONFIG_PATH="$INSTALLDIR" pkg-config --cflags "libbsoncxx >= 1.2.3")" bsoncxx_ldflags="$(PKG_CONFIG_PATH="$INSTALLDIR" pkg-config --libs "libbsoncxx >= 1.2.3")" g++ $bsoncxx_cflags -c example-a.cpp g++ $bsoncxx_cflags -c example-b.cpp g++ $bsoncxx_ldflags -o example example-a.o example-b.o ``` -------------------------------- ### Sample Command Monitoring Output Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/logging-monitoring/monitoring Example output generated when a find command is executed while monitoring is enabled. ```none Command started: find (request_id: 3) ``` -------------------------------- ### Configure mongocxx 3.0.x/3.1.x dependency paths Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/advanced-installation Explicitly defines the installation directories for libmongoc and libbson. ```bash cmake .. \ -DCMAKE_BUILD_TYPE=Release \ -DLIBMONGOC_DIR=$HOME/mongo-c-driver \ -DLIBBSON_DIR=$HOME/mongo-c-driver \ -DCMAKE_INSTALL_PREFIX=$HOME/mongo-cxx-driver ``` -------------------------------- ### Specify Multiple Compression Algorithms Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/network-compression Include the `compressors` option in your MongoDB URI to enable compression. This example specifies Snappy, Zstandard, and Zlib in that order. ```cpp #include #include #include int main() { mongocxx::instance instance; mongocxx::uri uri("mongodb://:/?compressors=snappy,zstd,zlib"); mongocxx::client client(uri); } ``` -------------------------------- ### Starting and Running a Transaction Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/crud/transactions This snippet shows how to initiate a client session and then execute a transaction function using the retry logic. It includes a try-catch block to handle any unrecoverable exceptions during the transaction process. ```cpp // Start a client session auto session = client.start_session(); try { run_with_retry(txn_func, session); } catch (const mongocxx::operation_exception& oe) { // Do something with error throw oe; } ``` -------------------------------- ### Build Project with Conan Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/advanced-installation Commands to install dependencies and build the project using Conan and CMake. ```bash $ conan install conanfile.txt --output-folder=build --build=missing $ cmake \ -B build \ -DCMAKE_TOOLCHAIN_FILE=conan_toolchain.cmake \ -DCMAKE_BUILD_TYPE=Release $ cmake --build build ``` -------------------------------- ### Monitor Command Started Events Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/logging-monitoring/monitoring Configures a client with an APM object to track and print details when database commands are initiated. ```cpp #include #include #include #include #include int main() { mongocxx::instance instance{}; int command_started_events = 0; mongocxx::options::apm apm_opts; apm_opts.on_command_started([&command_started_events](const mongocxx::events::command_started_event& event) { command_started_events++; std::cout << "Command started: " << event.command_name() << " (request_id: " << event.request_id() << ")" << std::endl; }); mongocxx::uri uri(""); mongocxx::options::client client_opts; client_opts.apm_opts(apm_opts); mongocxx::client client{uri, client_opts}; // Perform database operations std::cout << "Observed " << command_started_events << " command started events" << std::endl; return 0; } ``` -------------------------------- ### Initialize the C++ Driver Instance Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/instance Construct a mongocxx::instance object at the start of the application. This object must persist for the entire duration that any other MongoDB objects are in scope. ```cpp #include int main() { mongocxx::instance instance; } ``` -------------------------------- ### Explain Aggregation Operation in C++ Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/aggregation Use the `run_command()` method with a BSON document specifying the 'explain' command to get execution plans for an aggregation. This requires constructing a pipeline and then wrapping it within the explain command structure. ```cpp mongocxx::pipeline stages; stages.match(make_document(kvp("cuisine", "Bakery"))) .group(make_document(kvp("_id", "$borough"), kvp("count", make_document(kvp("$sum", 1)))))); auto command = make_document( kvp("explain", make_document( kvp("aggregate", "restaurants"), kvp("pipeline", stages.view_array()), kvp("cursor", make_document())))); auto result = db.run_command(command.view()); std::cout << bsoncxx::to_json(result) << std::endl; ``` -------------------------------- ### Integrate C++ Driver with pkg-config Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/include-link Compile and run a project using pkg-config for dependency management. Requires a full installation of the driver. ```bash $ c++ //examples/bsoncxx/view_and_value.cpp $(pkg-config --cflags libbsoncxx) -I/ $(pkg-config --libs libbsoncxx) -o view_and_value $ ./view_and_value { "team" : "platforms", "id" : { "$oid" : "67207262672b96dc3b0fc150" }, "members" : [ "tyler", "jason", "drew", "sam", "ernie", "john", "mark", "crystal" ] } Got key, key = team Got String! Got key, key = id Got ObjectId! Got key, key = members Got Array! array element: tyler array element: jason array element: drew array element: sam array element: ernie array element: john array element: mark array element: crystal as expected, we have a team document has 3 keys. document keys are: team id members ``` -------------------------------- ### Example Change Stream Event Output Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/logging-monitoring/change-streams A sample JSON representation of a change stream event containing a fullDocument field. ```bash { "_id" : { "_data" : "..." }, "operationType" : "update", "clusterTime" : { "$timestamp" : { ... } }, "wallTime" : { "$date" : ... }, "fullDocument" : { "_id" : { "$oid" : "..." }, "address" : { "building" : "202-24", "coord" : [ -73.925044200000002093, 40.559546199999999772 ], "street" : "Rockaway Point Boulevard", "zipcode" : "11697" }, "borough" : "Queens", "cuisine" : "Irish", "grades" : [ ... ], "name" : "Blarney Castle", "restaurant_id" : "40366356" }, "ns" : { "db" : "sample_restaurants", "coll" : "restaurants" }, "documentKey" : { "_id" : { "$oid" : "..." } }, "updateDescription" : { "updatedFields" : { "cuisine" : "Irish" }, "removedFields" : [ ], "truncatedArrays" : [ ] } } ``` -------------------------------- ### Acceptable Threading Example with Separate Clients Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/crud/thread-safety Shows a safe threading pattern where each thread uses its own distinct mongocxx::client. Individual synchronization of these separate clients is effective. ```cpp mongocxx::instance instance{}; mongocxx::uri uri{}; mongocxx::client c1{uri}; mongocxx::client c2{uri}; std::mutex c1_mtx{}; std::mutex c2_mtx{}; auto threadfunc = [](std::string dbname, mongocxx::client& client, std::mutex& mtx) { mtx.lock(); client[dbname]["col"].insert_one({}); mtx.unlock(); }; // These two clients are individually synchronized, so it is safe to share them between // threads. std::thread t1([&]() { threadfunc("db1", c1, c1_mtx); threadfunc("db2", c2, c2_mtx); }); std::thread t2([&]() { threadfunc("db2", c2, c2_mtx); threadfunc("db1", c1, c1_mtx); }); t1.join(); t2.join(); ``` -------------------------------- ### Ideal Threading Example with mongocxx::pool Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/crud/thread-safety Illustrates the recommended approach using mongocxx::pool for managing clients across threads. This pattern synchronizes client access while sharing a single background monitoring thread for efficiency. ```cpp mongocxx::instance instance{}; mongocxx::pool pool{mongocxx::uri{}}; auto threadfunc = [](mongocxx::client& client, std::string dbname) { auto col = client[dbname]["col"].insert_one({}); }; // Great! Using the pool allows the clients to be synchronized while sharing only one // background monitoring thread. std::thread t1 ([&]() { auto c = pool.acquire(); threadfunc(*c, "db1"); threadfunc(*c, "db2"); }); std::thread t2 ([&]() { auto c = pool.acquire(); threadfunc(*c, "db2"); threadfunc(*c, "db1"); }); t1.join(); t2.join(); ``` -------------------------------- ### Create and Use a Connection Pool Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/connection-pools Instantiate a mongocxx::pool with a connection URI. Each thread acquires a client using acquire(), performs operations, and the client is automatically returned to the pool when it goes out of scope. This example demonstrates creating a pool, launching three threads that each acquire a client, and inserting a document in each thread. ```cpp #include #include #include #include #include #include #include #include using bsoncxx::builder::basic::kvp; using bsoncxx::builder::basic::make_document; int main() { mongocxx::instance instance{}; mongocxx::uri uri{"mongodb://localhost:27017"}; mongocxx::pool pool{uri}; std::vector threads; // Creates multiple threads that each acquire a client from the pool for (int i = 0; i < 3; ++i) { threads.emplace_back([&pool, i]() { auto client = pool.acquire(); auto collection = (*client)["db"]["coll"]; // Inserts a sample document collection.insert_one(make_document(kvp("thread_id", i))); std::cout << "Thread " << i << " inserted a document" << std::endl; }); } // Waits for all threads to complete for (auto& thread : threads) { thread.join(); } std::cout << "All threads completed" << std::endl; return 0; } ``` -------------------------------- ### Configure Explicit Encryption for Insert Operation Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/security/in-use-encryption This example demonstrates configuring explicit encryption for an insert operation. It shows how to create a data key, set encryption options, encrypt a BSON value, and then insert the encrypted value into the database. ```cpp // Configure your MongoDB client's encryption options here class client_encryption client_encryption(std::move(client_encryption_opts)); auto data_key_id = client_encryption.create_data_key("local"); options::encrypt encrypt_opts{}; encrypt_opts.key_id(data_key_id.view()); encrypt_opts.algorithm(options::encrypt::encryption_algorithm::k_deterministic); // Explicitly encrypts a BSON value auto to_encrypt = bsoncxx::types::bson_value::make_value("secret message"); auto encrypted_message = client_encryption.encrypt(to_encrypt, encrypt_opts); // Explicitly decrypts a BSON value auto decrypted_message = client_encryption.decrypt(encrypted_message); // Inserts the encrypted value into the database coll.insert_one(make_document(kvp("encryptedField", encrypted_message))); ``` -------------------------------- ### Initialize application file Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/get-started Commands to navigate to the project directory and create the source file. ```bash cd cpp-quickstart touch quickstart.cpp ``` -------------------------------- ### Transaction Function Example Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/crud/transactions This function defines the operations to be performed within a transaction. It starts a transaction, inserts documents into two collections, and then commits the transaction with retry logic. ```cpp auto txn_func = [&](mongocxx::client_session& session) { auto& client = session.client(); // Define database and collection variables auto db = client["sample_mflix"]; auto movies_collection = db["movies"]; auto comments_collection = db["comments"]; // Define an options instance to explicitly set the write concern for the transaction operations mongocxx::options::transaction opts; mongocxx::write_concern wc; wc.acknowledge_level(mongocxx::write_concern::level::k_majority); opts.write_concern(wc); session.start_transaction(opts); // Attempt to insert documents into database collections try { movies_collection.insert_one(session, make_document(kvp("title", "Parasite"))); comments_collection.insert_one(session, make_document(kvp("name", "Anjali Patel"), kvp("text", "This is my new favorite movie!"))); } catch (const mongocxx::operation_exception& oe) { std::cout << "Caught exception during transaction, aborting." << std::endl; session.abort_transaction(); throw oe; } commit_with_retry(session); }; ``` -------------------------------- ### Instantiate Database and Collection Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/crud/query/count Set up the database and collection references for the sample_training dataset. ```cpp auto db = client["sample_training"]; auto collection = db["companies"]; ``` -------------------------------- ### Get Upserted ID from Replace One Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/crud/update/replace When using `upsert: true`, call `upserted_id()` on the result of `replace_one()` to retrieve the `_id` of the newly inserted document. This example replaces a document and, if an upsert occurs, prints the new document's ID. ```cpp mongocxx::options::replace opts{}; opts.upsert(true); auto query_filter = make_document(kvp("name", "In-N-Out Burger")); auto replace_doc = make_document(kvp("name", "Shake Shack")); auto result = collection.replace_one(query_filter.view(), replace_doc.view(), opts); auto id = result->upserted_id()->get_value(); std::cout << "Upserted ID: " << id.get_oid().value.to_string() << std::endl; ``` ```cli // Your ID value may differ Upserted ID: 67128c5ecc1f8c15ea26fcf8 ``` -------------------------------- ### Create project directory Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/get-started Use this command to initialize the project folder. ```bash mkdir cpp-quickstart ``` -------------------------------- ### Get Matched Count from Replace One Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/crud/update/replace Call the `matched_count()` member function on the result of `replace_one()` to determine how many documents matched the query filter. This example replaces a document named "Shake Shack" and then reports the number of matches. ```cpp auto query_filter = make_document(kvp("name", "Shake Shack")); auto replace_doc = make_document(kvp("name", "In-N-Out Burger")); auto result = collection.replace_one(query_filter.view(), replace_doc.view()); std::cout << "Matched documents: " << result->matched_count() << std::endl; ``` ```cli Matched documents: 11 ``` -------------------------------- ### Build and Run the Project Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/include-link Commands to compile the project and execute the resulting binary. ```none $ cd /home/user/project1 $ cmake -Bbuild $ cmake --build build ``` ```none $ ./build/view_and_value ``` -------------------------------- ### Run the 'hello' Command Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/run-command Execute the 'hello' command on a database to retrieve information about the replica set member's role. This requires a `mongocxx::database` instance and a BSON document specifying the command. ```cpp auto db = client["my_database"]; auto command = make_document(kvp("hello" , 1)); auto result = db.run_command(command.view()); std::cout << bsoncxx::to_json(result) << std::endl; ``` ```json { "topologyVersion" : { "processId" : ..., "counter" : ... }, "hosts" : [ ... ], "setName" : ..., "setVersion" : ..., "isWritablePrimary" : ..., "secondary" : ..., "primary" : ..., "tags" : { "region" : ..., "availabilityZone" : ..., "provider" : ..., "workloadType" : ..., "nodeType" : ..., "diskState" : ... }, "me" : ..., "electionId" : ..., "lastWrite" : ..., "lastWriteDate" : ..., "majorityOpTime" : ..., "majorityWriteDate" : ..., "maxBsonObjectSize" : ..., "maxMessageSizeBytes" : ..., "maxWriteBatchSize" : ..., "localTime" : ..., "logicalSessionTimeoutMinutes" : ..., "connectionId" : ..., "minWireVersion" : ..., "maxWireVersion" : ..., "readOnly" : ..., "ok" : ..., "$clusterTime" : ..., "signature" : ... } ``` -------------------------------- ### Inspect library install name Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/advanced-installation Checks the install name of the library to verify if it includes @rpath. ```bash otool -D $HOME/mongo-cxx-driver/lib/libmongocxx.dylib # Prints: # /Users/kevin.albertson/mongo-cxx-driver/lib/libmongocxx.dylib: # @rpath/libmongocxx._noabi.dylib ``` -------------------------------- ### Install MongoDB C++ Driver via Homebrew Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/advanced-installation Command to install the driver on macOS using Homebrew. ```bash brew install mongo-cxx-driver ``` -------------------------------- ### Configure C driver path for non-standard installations Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/advanced-installation Specifies the location of the C driver when it is installed in a non-standard directory. ```bash cmake .. \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_PREFIX_PATH=$HOME/mongo-c-driver \ -DCMAKE_INSTALL_PREFIX=$HOME/mongo-cxx-driver ``` -------------------------------- ### Vector Search Score Output Example Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/mongodb-vector-search Example JSON output showing document titles and their corresponding vector search scores. ```none { "title" : "About Time", "score" : 0.77101051807403564453 } { "title" : "Retroactive", "score" : 0.76004779338836669922 } { "title" : "A.P.E.X.", "score" : 0.7576859593391418457 } { "title" : "Timecop", "score" : 0.757656097412109375 } { "title" : "Back to the Future Part II", "score" : 0.75213932991027832031 } { "title" : "Thrill Seekers", "score" : 0.75099325180053710938 } { "title" : "Timerider: The Adventure of Lyle Swann", "score" : 0.75026416778564453125 } { "title" : "The Time Machine", "score" : 0.75025022029876708984 } { "title" : "The Time Traveler's Wife", "score" : 0.74949628114700317383 } { "title" : "The Final Countdown", "score" : 0.7469132542610168457 } ``` -------------------------------- ### Build with CMake and RPATH Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/advanced-installation Configure CMake to build and install applications using the C++ driver, noting potential RPATH clearing during installation. ```bash # Build application ``app`` using the C++ driver from a non-standard install. cmake \ -DCMAKE_PREFIX_PATH=$HOME/mongo-cxx-driver \ -DCMAKE_INSTALL_PREFIX=$HOME/app \ -DCMAKE_CXX_STANDARD=11 \ -Bcmake-build -S. cmake --build cmake-build --target app.out # Running app.out from build tree includes rpath to C++ driver. ./cmake-build ./cmake-build/app.out # Prints: "successfully connected with C++ driver" cmake --build cmake-build --target install # Running app.out from install tree does not include rpath to C++ driver. $HOME/app/bin/app.out # Prints "Library not loaded" error. ``` -------------------------------- ### Creating a Bulk Write Instance Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/crud/bulk-write Initialize a bulk write instance to store write instructions. ```cpp auto bulk = collection.create_bulk_write(); ``` -------------------------------- ### Example Change Stream Output Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/logging-monitoring/change-streams The JSON format of a change event captured by the stream. ```bash { "_id" : { "_data" : "..." }, "operationType" : "update", "clusterTime" : { "$timestamp" : { ... }, "wallTime" : { "$date" : ... }, "ns" : { "db" : "sample_restaurants", "coll" : "restaurants" }, "documentKey" : { "_id" : { "$oid" : "..." } }, "updateDescription" : { "updatedFields" : { "cuisine" : "Irish" }, "removedFields" : [ ], "truncatedArrays" : [ ] } } ``` -------------------------------- ### Initialize Database and Collection Variables Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/indexes/compound-index Instantiate the database and collection objects required to interact with the movies collection. ```cpp auto db = client["sample_mflix"]; auto collection = db["movies"]; ``` -------------------------------- ### Sample Application Structure Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/indexes This is a template for a C++ application using the MongoDB driver. Replace placeholders like '' with your deployment details. It includes basic error handling for driver operations. ```cpp #include #include #include #include #include #include #include using bsoncxx::builder::basic::kvp; using bsoncxx::builder::basic::make_document; int main() { try { mongocxx::instance instance; mongocxx::uri uri(""); mongocxx::client client(uri); auto database = client[""]; auto collection = database[""]; // Start example code here // End example code here } catch (const mongocxx::exception& e) { std::cout << "An exception occurred: " << e.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } ``` -------------------------------- ### Configure CMake with CMAKE_INSTALL_RPATH_USE_LINK_PATH Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/advanced-installation Ensure the RPATH is preserved in the installed executable by setting CMAKE_INSTALL_RPATH_USE_LINK_PATH to TRUE. ```bash # Build application ``app`` using the C++ driver from a non-standard install. # Use CMAKE_INSTALL_RPATH_USE_LINK_PATH=TRUE to keep rpath entry on installed app. cmake \ -DCMAKE_PREFIX_PATH=$HOME/mongo-cxx-driver \ -DCMAKE_INSTALL_PREFIX=$HOME/app \ -DCMAKE_INSTALL_RPATH_USE_LINK_PATH=TRUE \ -DCMAKE_CXX_STANDARD=11 \ -Bcmake-build -S. cmake --build cmake-build --target install $HOME/app/bin/app.out # Prints "successfully connected with C++ driver" ``` -------------------------------- ### Construct a BSON document with the basic builder Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/data-formats/working-with-bson Use make_document and kvp to create a BSON document in a single statement. ```cpp using bsoncxx::builder::basic::make_document; using bsoncxx::builder::basic::kvp; bsoncxx::document::value course = make_document( kvp("title","Poetry"), kvp("department","English")); ``` -------------------------------- ### Create mongocxx::client Instance Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/client Construct a mongocxx::uri object with your connection string, then pass it to the mongocxx::client constructor to establish a connection. Most applications need only one client instance. ```cpp #include #include #include int main() { mongocxx::instance instance; mongocxx::uri uri("mongodb://localhost:27017"); mongocxx::client client(uri); } ``` -------------------------------- ### Configure RPATH for non-standard installations Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/advanced-installation Sets the RPATH to the library directory to help the linker locate dependencies. ```bash cmake .. \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_INSTALL_PREFIX=$HOME/mongo-cxx-driver \ -DCMAKE_INSTALL_RPATH=$HOME/mongo-cxx-driver/lib ``` -------------------------------- ### Construct a BSON document with the basic builder across multiple statements Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/data-formats/working-with-bson Initialize a document object and use the append method to add key-value pairs before extracting the final value. ```cpp using bsoncxx::builder::basic::kvp; auto course_builder = bsoncxx::builder::basic::document{}; course_builder.append(kvp("title", "Literature"), kvp("department", "English")); bsoncxx::document::value course{course_builder.extract()}; ``` -------------------------------- ### Exclude Specific Fields in Projection Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/crud/query/project General syntax and example for excluding specific fields from the query result. ```cpp .projection(make_document(kvp("", 0))); ``` ```cpp mongocxx::options::find opts{}; opts.projection(make_document(kvp("grades", 0), kvp("address", 0))); auto cursor = collection.find(make_document(kvp("name", "Emerald Pub")), opts); for(auto&& doc : cursor) { std::cout << bsoncxx::to_json(doc) << std::endl; } ``` -------------------------------- ### Configure replace_one with hint option Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/crud/update/replace Demonstrates creating an index and applying it to a replace_one operation using the hint option. ```cpp auto index_specification = make_document(kvp("name", 1)); collection.create_index(index_specification.view()); mongocxx::options::replace opts{}; opts.hint(mongocxx::hint{"name_1"}); auto query_filter = make_document(kvp("name", "Nobu")); auto replace_doc = make_document(kvp("name", "La Bernadin")); auto result = collection.replace_one(query_filter.view(), replace_doc.view(), opts); ``` -------------------------------- ### Exclude _id Field in Projection Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/crud/query/project Example of including specific fields while explicitly excluding the _id field. ```cpp mongocxx::options::find opts{}; opts.projection(make_document(kvp("_id", 0), kvp("name", 1), kvp("cuisine", 1), kvp("borough", 1))); auto cursor = collection.find(make_document(kvp("name", "Emerald Pub")), opts); for(auto&& doc : cursor) { std::cout << bsoncxx::to_json(doc) << std::endl; } ``` -------------------------------- ### Monitor Server Opening Events with C++ Driver Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/logging-monitoring/monitoring This snippet demonstrates how to monitor server opening events by configuring a callback function using `mongocxx::options::apm::on_server_opening()`. The callback prints the host and port of newly opened servers. Ensure you have the necessary includes and a valid connection string URI. ```cpp #include #include #include #include #include int main() { mongocxx::instance instance{}; int server_opening_events = 0; mongocxx::options::apm apm_opts; apm_opts.on_server_opening([&server_opening_events](const mongocxx::events::server_opening_event& event) { server_opening_events++; std::cout << "Server opening: " << event.host() << ":" << event.port() << std::endl; }); mongocxx::uri uri(""); mongocxx::options::client client_opts; client_opts.apm_opts(apm_opts); mongocxx::client client{uri, client_opts}; // Perform database operations std::cout << "Observed " << server_opening_events << " server opening events" << std::endl; return 0; } ``` -------------------------------- ### Include Specific Fields in Projection Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/crud/query/project Example of including name, cuisine, and borough fields in the query result. ```cpp mongocxx::options::find opts{}; opts.projection(make_document(kvp("name", 1), kvp("cuisine", 1), kvp("borough", 1))); auto cursor = collection.find(make_document(kvp("name", "Emerald Pub")), opts); for(auto&& doc : cursor) { std::cout << bsoncxx::to_json(doc) << std::endl; } ``` -------------------------------- ### Configure X.509 Authentication in Connection URI Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/security/authentication/x509 Use this connection string format to enable X.509 authentication. Ensure you replace placeholders with your actual hostname, port, and the path to your client certificate/key file. ```cpp auto uri = mongocxx::uri("mongodb://:/?" "tls=true&tlsCertificateKeyFile=path/to/client.pem&authMechanism=MONGODB-X509"); auto client = mongocxx::client(uri); ``` -------------------------------- ### Example Search Query Output Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/mongodb-search Represents the expected JSON output format when executing the compound search query. ```none { "title" : "New York, New York", "score" : 6.7870168685913085938 } { "title" : "New York", "score" : 6.2591872215270996094 } { "title" : "New York Doll", "score" : 5.3819599151611328125 } { "title" : "Escape from New York", "score" : 4.7203946113586425781 } { "title" : "Autumn in New York", "score" : 4.7203946113586425781 } { "title" : "Gangs of New York", "score" : 4.7203946113586425781 } { "title" : "Sleepless in New York", "score" : 4.7203946113586425781 } { "title" : "Sherlock Holmes in New York", "score" : 4.2036685943603515625 } { "title" : "New York: A Documentary Film", "score" : 4.2036685943603515625 } { "title" : "An Englishman in New York", "score" : 4.2036685943603515625 } ``` -------------------------------- ### Troubleshoot macOS library loading errors Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/advanced-installation Example of a runtime error caused by missing RPATH configuration on macOS. ```bash # Tell pkg-config where to find C++ driver installation. export PKG_CONFIG_PATH=$HOME/mongo-cxx-driver/lib/pkgconfig clang++ app.cpp -std=c++11 $(pkg-config --cflags --libs libmongocxx) -o ./app.out ./app.out # Prints the following error: # dyld[3217]: Library not loaded: '@rpath/libmongocxx._noabi.dylib' # Referenced from: '/Users/kevin.albertson/code/app.out' # Reason: tried: '/usr/local/lib/libmongocxx._noabi.dylib' (no such file), '/usr/lib/libmongocxx._noabi.dylib' (no such file) # zsh: abort ./app.out ``` -------------------------------- ### Run 'connectionStatus' with 'showPrivileges' Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/run-command Execute the 'connectionStatus' command with the 'showPrivileges' option set to true to retrieve detailed privilege information for authenticated users. This requires a `mongocxx::database` instance and a BSON document specifying the command and its options. ```cpp auto db = client["my_database"]; auto command = make_document(kvp("connectionStatus" , 1), kvp("showPrivileges", true)); auto result = db.run_command(command.view()); std::cout << bsoncxx::to_json(result) << std::endl; ``` ```json { "authInfo" : { "authenticatedUsers" : [ { "user" : ..., "db" : ... } ], "authenticatedUserRoles" : [ { "role" : ..., "db" : ... } ], "authenticatedUserPrivileges" : [ { "resource" : { "db" : "", "collection" : "" }, "actions" : [ ... ] }, { "resource" : { "db" : "config", "collection" : "system.sessions" }, "actions" : [ ... ] }, ..., { "resource" : { "db" : "", "collection" : "" }, "actions" : [ ... ] } ] }, "ok" : 1 } ``` -------------------------------- ### Integrate Vcpkg with Visual Studio Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/advanced-installation Command to enable Visual Studio integration for Vcpkg. ```bash vcpkg integrate install ``` -------------------------------- ### Configure Connection via URI Source: https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/connect/connection-options Pass connection options as key-value pairs directly within the connection URI string. ```cpp #include #include #include int main() { mongocxx::instance instance; mongocxx::uri uri("mongodb://:/?tls=true&tlsCertificateKeyFile=path/to/file.pem"); mongocxx::client client(uri); } ```