### Navigate to Example Directory Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/examples/README.md Change to the mongocxx examples directory to run individual example files. Ensure mongod is running on the default port. ```bash cd examples/mongocxx ``` -------------------------------- ### Build Project Examples with CMake Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/examples/README.md Build specific project examples, like those in the 'shared' directory, using the provided build script. This assumes libmongoc and mongocxx are installed. ```bash ./build.sh ``` -------------------------------- ### Build MongoDB C++ Driver Examples Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/examples/README.md Compile the example code for the MongoDB C++ Driver after cloning the repository and installing the driver. Ensure mongod is running. ```bash make examples ``` -------------------------------- ### Install License and Readme Files Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/CMakeLists.txt Installs the LICENSE, README.md, and THIRD-PARTY-NOTICES files to the data directory of the installation prefix. ```cmake install(FILES LICENSE README.md THIRD-PARTY-NOTICES DESTINATION ${CMAKE_INSTALL_DATADIR}/mongo-cxx-driver ) ``` -------------------------------- ### Run a MongoDB C++ Driver Example Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/examples/README.md Execute a compiled example file, such as 'aggregate', from the mongocxx examples directory. This requires mongod to be running. ```bash ./aggregate ``` -------------------------------- ### Setup Python Virtual Environment for Release Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/etc/releasing.md Creates and activates a Python 3 virtual environment using 'uv' to install necessary packages for API documentation generation and release management. The environment is isolated using a temporary directory. ```bash # Outside the mongo-cxx-driver-release directory! export UV_PROJECT_ENVIRONMENT="$(mktemp -d)" # Install required packages into a new virtual environment. uv sync --frozen --group apidocs --group make_release # Activate the virtual environment. source "$UV_PROJECT_ENVIRONMENT/bin/activate" ``` -------------------------------- ### Generated Header Configuration Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/etc/coding_guidelines.md Example of the directory structure for generated header input files and the CMakeLists.txt responsible for their configuration and installation. ```text lib/ ├── v1/ │ ├── config/ │ │ ├── config.hpp.in # Input file to generate config.hpp. │ │ └── ... │ └── ... └── CMakeLists.txt # Responsible for configuration and installation. ``` -------------------------------- ### Install MongoDB C++ Driver Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/AGENTS.md This command installs the built project. It should be run after the build step. ```bash cmake --install build ``` -------------------------------- ### Install BSONcxx Headers with CMake Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/src/bsoncxx/include/CMakeLists.txt Installs BSONcxx header files to the destination directory. Excludes documentation files from installation. ```cmake install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} COMPONENT dev FILES_MATCHING PATTERN "*.hpp" PATTERN "bsoncxx/docs/*" EXCLUDE PATTERN "bsoncxx/docs" EXCLUDE ) ``` -------------------------------- ### Basic Logger Usage Example Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/api/mongocxx/examples/logger.md Demonstrates the basic usage of the logger functionality in the MongoDB C++ driver. No specific setup is required beyond including the necessary headers. ```cpp #include #include "mongocxx/config/prelude.hpp" // For the sake of example, disable mongocxx's default logging. // This example is demonstrating how to use mongocxx's logger. // mongocxx::logger::instance().set_severity_level(mongocxx::log_severity::k_none); #include "mongocxx/logger.hpp" using namespace mongocxx; int main() { logger::instance().log(log_severity::k_error, "This is an error message."); logger::instance().log(log_severity::k_warning, "This is a warning message."); logger::instance().log(log_severity::k_info, "This is an informational message."); logger::instance().log(log_severity::k_debug, "This is a debug message."); return 0; } ``` -------------------------------- ### Verify Tool Installation Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/etc/releasing.md Check if essential documentation tools like doxygen, hugo, and rsync are installed and accessible in the system's PATH. This is a prerequisite for building documentation. ```bash command -V doxygen hugo rsync ``` -------------------------------- ### Directory Structure Example Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/extras/docker/README.md This shows the expected file structure for the Docker build, with Dockerfile and ping.c in the same directory. ```shell $ tree . . ├── Dockerfile └── ping.c ``` -------------------------------- ### Dockerfile for MongoDB C++ Driver Ping Example Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/extras/docker/README.md This Dockerfile sets up an environment to compile and run a C++ program that pings a MongoDB deployment using the MongoDB C++ Driver. It installs necessary build tools and copies the C++ source file. ```Dockerfile FROM mongodb/mongo-cxx-driver:3.10.1-redhat-ubi-9.4 WORKDIR /build RUN microdnf upgrade -y && microdnf install -y g++ COPY ping.cpp /build/ RUN g++ \ -o ping \ ping.cpp \ -I/usr/local/include/bsoncxx/v_noabi/ \ -I/usr/local/include/mongocxx/v_noabi/ \ -lmongocxx \ -lbsoncxx CMD /build/ping ``` -------------------------------- ### Glob and Add bsoncxx Examples Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/examples/CMakeLists.txt Finds all C++ source files in the 'bsoncxx' directory and adds them as executables using the 'add_examples_executable' function, linking against the bsoncxx library. ```cmake file(GLOB_RECURSE bsoncxx_examples_sources RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} CONFIGURE_DEPENDS "bsoncxx/*.cpp" ) foreach(source ${bsoncxx_examples_sources}) add_examples_executable(${source} LIBRARIES bsoncxx_target) endforeach() ``` -------------------------------- ### Glob and Add mongocxx Examples Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/examples/CMakeLists.txt Finds all C++ source files in the 'mongocxx' directory and adds them as executables. It conditionally links the Threads library for specific examples and excludes encryption examples from the run suite. ```cmake file(GLOB_RECURSE mongocxx_examples_sources RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} CONFIGURE_DEPENDS "mongocxx/*.cpp" ) foreach(source ${mongocxx_examples_sources}) set(extra_libs "") set(add_to_run_examples ON) if (${source} MATCHES "pool|change_streams_examples") list(APPEND extra_libs Threads::Threads) endif() # Don't run the CSFLE examples as part of the suite; needs mongocryptd running. if (${source} MATCHES "encryption") set(add_to_run_examples OFF) endif() add_examples_executable(${source} LIBRARIES mongocxx_target ${extra_libs} ADD_TO_RUN_EXAMPLES ${add_to_run_examples} ) endforeach() ``` -------------------------------- ### Component File Structure Example Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/etc/coding_guidelines.md Illustrates the typical file organization for a component named 'foo' within the bsoncxx library, including include, lib, and test directories with versioned ABI paths. ```text src// ├── include/bsoncxx/v/ │ ├── foo-fwd.hpp (Forward Header, optional) │ └── foo.hpp (Normal Header) ├── lib/bsoncxx/v/ │ ├── foo.hh (Internal / Private Header, optional) │ └── foo.cpp (Implementation / Source File) ├── test/v/ │ ├── foo.hh (Test Header, optional) │ └── foo.cpp (Test Implementation / Source File) └── ... ``` -------------------------------- ### Public Header Structure Example Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/etc/coding_guidelines.md Illustrates the directory structure for public headers, including ABI-specific namespaces and detail subdirectories. ```text include/ ├── bsoncxx/ │ ├── v_noabi/ │ │ └── bsoncxx/ │ │ ├── fwd.hpp │ │ ├── detail/ │ │ │ └── ... │ │ ├── document/ │ │ │ ├── value-fwd.hpp │ │ │ ├── value.hpp │ │ │ └── ... │ │ └── ... │ └── v1/ │ ├── fwd.hpp │ ├── detail/ │ │ └── ... │ ├── document/ │ │ ├── value-fwd.hpp │ │ ├── value.hpp │ │ └── ... │ └── ... └── CMakeLists.txt ``` -------------------------------- ### Install CMake Configuration Files Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/src/mongocxx/cmake/CMakeLists.txt Installs the generated CMake configuration files (`mongocxxConfigVersion.cmake` and `mongocxxConfig.cmake`) into the CMake package directory. This makes the driver discoverable by `find_package`. ```cmake install( FILES ${CMAKE_CURRENT_BINARY_DIR}/mongocxxConfigVersion.cmake ${CMAKE_CURRENT_BINARY_DIR}/mongocxxConfig.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/mongocxx-$CACHE{MONGOCXX_VERSION} COMPONENT Devel ) ``` -------------------------------- ### Conditional Uninstall Target Setup Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/CMakeLists.txt Conditionally enables the uninstall functionality if ENABLE_UNINSTALL is set. It determines the appropriate uninstall script name based on the operating system (Windows or others) and sets the installation directory. ```cmake if(ENABLE_UNINSTALL) if(WIN32) set(UNINSTALL_PROG "uninstall.cmd") else() set(UNINSTALL_PROG "uninstall.sh") endif() set(UNINSTALL_PROG_DIR "${CMAKE_INSTALL_DATADIR}/mongo-cxx-driver") # Create uninstall program and associated uninstall target # # This needs to be last (after all other add_subdirectory calls) to ensure # that the generated uninstall program is complete and correct add_subdirectory(generate_uninstall) endif() ``` -------------------------------- ### Create MongoDB Client with TLS Options Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/api/mongocxx/examples/clients.md Demonstrates how to configure a MongoDB client for TLS/SSL connections. This requires proper TLS setup on both the client and server. ```cpp auto uri = mongocxx::uri{ "mongodb://localhost:27017" }; auto opts = mongocxx::options::client{}; opts.tls_options(mongocxx::options::tls_options{}); auto client = mongocxx::client{ uri, opts }; ``` -------------------------------- ### Build Docker Image for C++ MongoDB Ping Example Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/extras/docker/README.md Command to build the Docker image named 'mongocxx-ping' from the current directory containing the Dockerfile and ping.cpp. ```shell docker build . -t mongocxx-ping ``` -------------------------------- ### Define Custom Build Targets Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/examples/CMakeLists.txt Sets up custom targets for building and running examples, including API, bsoncxx, and mongocxx specific examples. These targets help organize the build process. ```cmake add_custom_target(examples) add_custom_target(run-examples) add_custom_target(run-api-examples) add_custom_target(run-bsoncxx-examples) add_custom_target(run-mongocxx-examples) add_dependencies(run-examples run-api-examples run-bsoncxx-examples run-mongocxx-examples ) ``` -------------------------------- ### Configure and Build C++ Driver Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/etc/releasing.md Configure and build the C++ Driver using CMake. Use the auto-downloaded C Driver sources and do not reuse existing installations. ```bash cmake -S . -B build cmake --build build ``` -------------------------------- ### Generate and Install Public Headers Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/src/mongocxx/lib/CMakeLists.txt Generates and installs public configuration and version headers for the v1 ABI. It also configures forward declaration headers for the v_noabi and v1 ABIs. ```cmake if(1) configure_file( mongocxx/v1/config/config.hpp.in mongocxx/v1/config/config.hpp ) configure_file( mongocxx/v1/config/version.hpp.in mongocxx/v1/config/version.hpp ) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/mongocxx/v1/config/config.hpp ${CMAKE_CURRENT_BINARY_DIR}/mongocxx/v1/config/version.hpp DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/mongocxx/v1/config COMPONENT dev ) configure_file( mongocxx/v_noabi/mongocxx/config/config.hpp.in mongocxx/v_noabi/mongocxx/config/config.hpp ) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/mongocxx/v_noabi/mongocxx/config/config.hpp DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/mongocxx/v_noabi/mongocxx/config COMPONENT dev ) if(1) file(GLOB_RECURSE mongocxx_v_noabi_fwd_headers RELATIVE "${PROJECT_SOURCE_DIR}/include/mongocxx/v_noabi" CONFIGURE_DEPENDS "${PROJECT_SOURCE_DIR}/include/mongocxx/v_noabi/mongocxx/*-fwd.hpp" ) list(SORT mongocxx_v_noabi_fwd_headers) if("${mongocxx_v_noabi_fwd_headers}" STREQUAL "") message(FATAL_ERROR "No mongocxx v_noabi forward headers found by file(GLOB_RECURSE)") endif() set(MONGOCXX_V_NOABI_FWD_INCLUDES "") foreach(header IN LISTS mongocxx_v_noabi_fwd_headers) string(APPEND MONGOCXX_V_NOABI_FWD_INCLUDES "#include <${header}> // IWYU pragma: export\n") endforeach() string(STRIP "${MONGOCXX_V_NOABI_FWD_INCLUDES}" MONGOCXX_V_NOABI_FWD_INCLUDES) configure_file( mongocxx/v_noabi/mongocxx/fwd.hpp.in mongocxx/v_noabi/mongocxx/fwd.hpp @ONLY ) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/mongocxx/v_noabi/mongocxx/fwd.hpp DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/mongocxx/v_noabi/mongocxx COMPONENT dev ) endif() if(1) file(GLOB_RECURSE mongocxx_v1_fwd_headers RELATIVE "${PROJECT_SOURCE_DIR}/include" CONFIGURE_DEPENDS "${PROJECT_SOURCE_DIR}/include/mongocxx/v1/*-fwd.hpp" ) list(SORT mongocxx_v1_fwd_headers) if("${mongocxx_v1_fwd_headers}" STREQUAL "") message(FATAL_ERROR "No mongocxx v1 forward headers found by file(GLOB_RECURSE)") endif() set(MONGOCXX_V1_FWD_INCLUDES "") foreach(header IN LISTS mongocxx_v1_fwd_headers) string(APPEND MONGOCXX_V1_FWD_INCLUDES "#include <${header}> // IWYU pragma: export\n") endforeach() string(STRIP "${MONGOCXX_V1_FWD_INCLUDES}" MONGOCXX_V1_FWD_INCLUDES) configure_file( mongocxx/v1/fwd.hpp.in mongocxx/v1/fwd.hpp @ONLY ) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/mongocxx/v1/fwd.hpp DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/mongocxx/v1 COMPONENT dev ) endif() endif() ``` -------------------------------- ### Dockerfile for C++ Driver Setup Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/extras/docker/README.md This Dockerfile is used to set up an environment for the mongo-cxx-driver. Ensure you have access to a MongoDB database server, such as through Atlas. ```Dockerfile FROM redhat/ubi9:9.4 RUN yum update -y && \ yum install -y \ git \ make \ cmake \ gcc-c++ \ openssl-devel \ libuuid-devel && \ yum clean all RUN git clone https://github.com/mongodb/mongo-cxx-driver.git --branch 3.10.1 --depth 1 RUN cd mongo-cxx-driver && \ mkdir -p /build/Release && \ cd /build/Release && \ cmake -DCMAKE_BUILD_TYPE=Release -IDRIVER_VERSION=3.10.1 -DCMAKE_INSTALL_PREFIX=/usr/local/mongo-cxx-driver ../../src && \ make -j$(nproc) && \ make install RUN rm -rf /build RUN rm -rf /mongo-cxx-driver CMD ["bash"] ``` -------------------------------- ### Basic BSON Validation Example Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/api/bsoncxx/examples/validation.md Illustrates fundamental BSON validation without a specific validator. ```cpp #include #include #include #include #include #include #include #include #include using namespace bsoncxx::builder::basic; TEST_CASE("basic validation", "[]") { // The following example demonstrates basic validation. // The "basic" validator is implicitly used when no validator is specified. // This validator ensures that the document is a valid BSON document. // For example, it checks for correct data types and structure. auto doc = document( open_document << "name" << "MongoDB" << open_document << "type" << "Database" << close_document << close_document )(); // The document is valid by default if it can be constructed. // No explicit validation call is needed here as the driver handles it. // If the document were invalid, construction would fail or throw an exception. // Example of converting to JSON to show the structure (optional) // std::cout << bsoncxx::to_json(doc) << std::endl; } ``` -------------------------------- ### Create Array from Raw Bytes as View Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/api/bsoncxx/examples/bson_documents/create_array.md This example shows how to create a BSON array from raw bytes, treating it as a view. This is efficient for reading existing BSON data. ```cpp auto arr_view = bsoncxx::array::view(raw_bytes); ``` -------------------------------- ### Class Declaration Order Example Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/etc/coding_guidelines.md Demonstrates the recommended order for declaring members in a C++ class, prioritizing special member functions and constructors to align with ownership semantics and the Rule of Zero. ```cpp class Example : public Bases... { private: // Data members. public: ~Example(); Example(Example&& other) noexcept; Example& operator=(Example&& other) noexcept; Example(Example const& other); Example& operator=(Example const& other); Example(); // When default-constructible. Example(Args...); // Other constructors. // Public API. private: // Private members. }; ``` -------------------------------- ### Basic Change Stream Usage Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/api/mongocxx/examples/change_streams.md Shows the basic usage of a change stream to monitor for document inserts. This example assumes a collection named 'testcollection'. ```cpp #include #include #include #include #include #include #include int main() { // Initialize the MongoDB C++ driver mongocxx::instance instance{}; mongocxx::client client{mongocxx::uri{}}; // Access a collection mongocxx::collection coll = client[ "testdb" ][ "testcollection" ]; // Obtain a change stream from the collection auto change_stream = coll.watch(); std::cout << "Monitoring for changes in 'testcollection'..." << std::endl; // Iterate over the change stream to detect changes for (auto&& change : change_stream) { // Check if the change is an 'insert' operation if (change.operation_type() == mongocxx::change_stream::operation_type::k_insert) { std::cout << "Insert detected: " << bsoncxx::to_json(change.full_document()) << std::endl; } } return 0; } ``` -------------------------------- ### Docker Image Test Success Output Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/etc/releasing.md Example output indicating a successful Docker image test, showing the driver version that was tested. ```text mongo-cxx-driver version: 3.9.0 THE redhat-ubi-9.3 IMAGE WORKS! ``` -------------------------------- ### Create BSON Document using Basic Builder Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/api/bsoncxx/examples/bson_documents/create_doc.md This example uses the basic builder API to construct a BSON document programmatically. It's suitable for dynamic document creation. ```cpp using bsoncxx::builder::basic::make_document; auto doc = make_document( bsoncxx::builder::basic::kvp("name", "MongoDB"), bsoncxx::builder::basic::kvp("type", "Database") ); ``` -------------------------------- ### Create BSON Document from Extended JSON String Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/api/bsoncxx/examples/bson_documents/create_doc.md This example demonstrates creating a BSON document from an extended JSON string, allowing for BSON-specific types. ```cpp auto doc = bsoncxx::from_json( "{ \"date\": { \"$date\": \"2023-01-01T00:00:00.000Z\" } }" ); ``` -------------------------------- ### Create BSON Document View from Raw Bytes Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/api/bsoncxx/examples/bson_documents/create_doc.md This example shows how to create a BSON document view from raw BSON bytes. Views provide read-only access without copying. ```cpp using bsoncxx::builder::basic::document; using bsoncxx::builder::basic::kvp; document builder; builder.append(kvp("key", "value")); auto view = builder.extract().view(); ``` -------------------------------- ### Handle Regular Exceptions in C++ Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/api/mongocxx/examples/operation_exceptions.md Example demonstrating how to catch and handle regular exceptions. Note that the mongocxx::server_error_category is overloaded, so error code values may vary in context. ```cpp auto client = mongocxx::client{}; auto collection = client["db"]["collection"]; try { collection.insert_one( document{} << "hello" << "world" << finalize ); } catch (const mongocxx::server_error_category &e) { // Handle exception } ``` -------------------------------- ### Glob and Add API Examples Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/examples/CMakeLists.txt Finds C++ source files in the 'api' directory, excluding 'runner.cpp', and adds them to the 'api-runner' executable. It also defines unique entry function names for each component. ```cmake file(GLOB_RECURSE api_examples_sources RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} CONFIGURE_DEPENDS "api/*.cpp" ) list(REMOVE_ITEM api_examples_sources "api/runner.cpp") function (add_abi_examples) # Avoid MAX_PATH errors on Windows due to long target names by using a single `api-runner` . add_examples_executable(api/runner.cpp LIBRARIES mongocxx_target Threads::Threads) # Define a unique entry function name per component. foreach (source ${api_examples_sources}) target_sources (api-runner PRIVATE ${source}) # path/to/source.cpp -> source get_filename_component(name ${source} NAME_WE) # path/to/source.cpp -> path/to get_filename_component(subdir ${source} DIRECTORY) # path/to/source -> path_to_source string(REPLACE "/" "_" component_name "${subdir}/${name}") # Define a unique component name for each component to be registered with the runner. ``` -------------------------------- ### Show make_release.py Help Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/etc/releasing.md Run the release script with `--help` to view all available options and configurations. ```bash python ./etc/make_release.py --help ``` -------------------------------- ### Create Client Session (With Options) Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/api/mongocxx/examples/client_sessions.md Shows how to create a client session with specific options. This allows for more control over session behavior, such as read preference. ```cpp #include #include #include #include int main() { // Initialize the MongoDB driver mongocxx::instance instance{}; // Create a MongoDB client mongocxx::client client{mongocxx::uri{}}; // Define session options mongocxx::options::client_session session_options{}; session_options.read_preference(mongocxx::read_preference{mongocxx::read_preference::mode::k_secondary}); // Create a client session with options auto session = client.start_session(session_options); std::cout << "Client session created with options successfully." << std::endl; return 0; } ``` -------------------------------- ### Create MongoDB Client (Basic) Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/api/mongocxx/examples/clients.md Demonstrates the basic usage for creating a MongoDB client instance. ```cpp auto client = mongocxx::client{}; ``` -------------------------------- ### Create Client Session (Basic) Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/api/mongocxx/examples/client_sessions.md Demonstrates the basic creation of a client session. Ensure you have a MongoDB client instance available. ```cpp #include #include #include int main() { // Initialize the MongoDB driver mongocxx::instance instance{}; // Create a MongoDB client mongocxx::client client{mongocxx::uri{}}; // Create a client session auto session = client.start_session(); std::cout << "Client session created successfully." << std::endl; return 0; } ``` -------------------------------- ### Custom Initialization with jQuery (JavaScript) Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/themes/mongodb/static/lib/highlight/README.md This example shows how to manually highlight code blocks using highlightBlock within a jQuery document ready function. It iterates over all <pre><code> elements. ```javascript $(document).ready(function() { $('pre code').each(function(i, block) { hljs.highlightBlock(block); }); }); ``` -------------------------------- ### List Databases Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/api/mongocxx/examples/clients.md Demonstrates how to list all available databases on the MongoDB server using a client instance. ```cpp auto databases = client.list_databases(); for (const auto& db_info : databases) { // Process database information } ``` -------------------------------- ### List Databases with Options Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/api/mongocxx/examples/clients.md Shows how to list databases with specific options, such as filtering by name using a regular expression. ```cpp auto databases = client.list_databases(mongocxx::options::list_databases{}); for (const auto& db_info : databases) { // Process database information } ``` -------------------------------- ### Install CMake Export File Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/src/mongocxx/cmake/CMakeLists.txt Installs the CMake export file `mongocxx_targets.cmake` which allows CMake to find the installed targets of the mongocxx library. This is crucial for projects that depend on the mongocxx driver. ```cmake install(EXPORT mongocxx_targets NAMESPACE mongo:: FILE mongocxx_targets.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/mongocxx-$CACHE{MONGOCXX_VERSION} ) ``` -------------------------------- ### Add Example Executable Function Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/examples/CMakeLists.txt A CMake function to add an executable for examples. It handles source file processing, library linking, compile options, and dependency management for running examples. ```cmake function(add_examples_executable source) set(opt_args "") set(single_args "ADD_TO_RUN_EXAMPLES") set(multi_args "LIBRARIES") cmake_parse_arguments(PARSED "${opt_args}" "${single_args}" "${multi_args}" ${ARGN}) if(NOT "${PARSED_UNPARSED_ARGUMENTS}" STREQUAL "") message(FATAL_ERROR "unrecognized argument: ${PARSED_UNPARSED_ARGUMENTS}") endif() if ("${PARSED_ADD_TO_RUN_EXAMPLES}" STREQUAL "") set(PARSED_ADD_TO_RUN_EXAMPLES "ON") # Default to ON. endif () # path/to/source.cpp -> source get_filename_component(name ${source} NAME_WE) # path/to/source.cpp -> path/to get_filename_component(subdir ${source} DIRECTORY) # path/to/source -> path-to-source string(REPLACE "/" "-" target_name "${subdir}/${name}") add_executable(${target_name} EXCLUDE_FROM_ALL ${source}) target_link_libraries(${target_name} PRIVATE ${PARSED_LIBRARIES}) # Permit `#include `. target_include_directories(${target_name} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/..) # Keep executables in separate directories. set_target_properties(${target_name} PROPERTIES OUTPUT_NAME ${name} RUNTIME_OUTPUT_DIRECTORY ${subdir} ) # Use `__vectorcall` by default with MSVC to catch missing `__cdecl`. target_compile_options(${target_name} PRIVATE "<$:/Gv>") # Keep build and run targets completely separate. add_dependencies(examples ${target_name}) # Use full path to avoid implicit build dependency. if (isMultiConfig) add_custom_target(run-examples-${target_name} COMMAND "${subdir}/$/${name}") else () add_custom_target(run-examples-${target_name} COMMAND "${subdir}/${name}") endif () set (type "") if (${source} MATCHES "^api/") set (type "api") elseif (${source} MATCHES "^bsoncxx/") set (type "bsoncxx") elseif (${source} MATCHES "^mongocxx/") set (type "mongocxx") else () message (FATAL_ERROR "unexpected subdirectory ${subdir}") endif () if (PARSED_ADD_TO_RUN_EXAMPLES) add_dependencies(run-${type}-examples run-examples-${target_name}) endif () endfunction() ``` -------------------------------- ### Install C++ Driver Headers Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/src/mongocxx/include/CMakeLists.txt Installs header files for the C++ driver. Ensure the destination and component are correctly set for your build environment. ```cmake install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} COMPONENT dev FILES_MATCHING PATTERN "*.hpp" PATTERN "mongocxx/docs/*" EXCLUDE PATTERN "mongocxx/docs" EXCLUDE ) ``` -------------------------------- ### Use Client Session (Basic) Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/api/mongocxx/examples/client_sessions.md Illustrates the basic usage of a client session for operations. Operations performed within a session benefit from causal consistency. ```cpp #include #include #include #include #include #include int main() { // Initialize the MongoDB driver mongocxx::instance instance{}; // Create a MongoDB client mongocxx::client client{mongocxx::uri{}}; mongocxx::database db = client["testdb"]; mongocxx::collection coll = db["testcoll"]; // Create a client session auto session = client.start_session(); // Insert a document using the session using bsoncxx::builder::stream::open_document; using bsoncxx::builder::stream::close_document; using bsoncxx::builder::stream::finalize; auto builder = bsoncxx::builder::stream::document{}; bsoncxx::document::value doc_to_insert = builder << "name" << "MongoDB C++ Driver" << "type" << "Database" << "count" << 1 << "v" << 2 << finalize; coll.insert_one(std::move(doc_to_insert), mongocxx::options::insert{session.get_id()}); std::cout << "Document inserted using client session." << std::endl; return 0; } ``` -------------------------------- ### Query MongoDB URI - All Options Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/api/mongocxx/examples/uri.md Demonstrates retrieving all options from a comprehensive MongoDB URI. ```cpp #include #include int main() { mongocxx::uri uri("mongodb://user:password@host1:27017,host2:27017/database?replicaSet=rs0&w=majority&authSource=admin"); std::cout << "URI: " << uri.to_string() << std::endl; auto credentials = uri.user_info(); if (credentials) { std::cout << "Username: " << credentials->username() << std::endl; std::cout << "Password: " << credentials->password() << std::endl; } for (const auto& host : uri.hosts()) { std::cout << "Host: " << host.host << ":" << host.port << std::endl; } auto options = uri.options(); std::cout << "Replica Set: " << options.get_optional("replicaSet").value_or("N/A") << std::endl; std::cout << "Write Concern: " << options.get_optional("w").value_or("N/A") << std::endl; std::cout << "Auth Source: " << options.get_optional("authSource").value_or("N/A") << std::endl; return 0; } ``` -------------------------------- ### Add Subdirectories Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/CMakeLists.txt Adds subdirectories 'src', 'examples', 'benchmark', 'cmake', 'data', 'docs', and 'etc' to the CMake build. 'examples' and 'benchmark' are excluded from the default build. ```cmake add_subdirectory(src) add_subdirectory(examples EXCLUDE_FROM_ALL) add_subdirectory(benchmark EXCLUDE_FROM_ALL) # Implement 'dist' target # # CMake does not implement anything like 'dist' from autotools. # This implementation is based on the one in GnuCash. add_subdirectory(cmake) add_subdirectory(data) add_subdirectory(docs) add_subdirectory(etc) ``` -------------------------------- ### Create a Collection With Options Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/api/mongocxx/examples/databases.md Shows how to create a collection with specific options, such as capped size or validation rules. This allows for more control over collection behavior. ```cpp #include #include #include #include int main() { mongocxx::instance instance{}; mongocxx::client client{}; auto db = client[ "testdb" ]; // Define options for the new collection mongocxx::options::collection options{}; options.capped(true); options.max_size(1024 * 1024); // 1MB capped size // Create the collection with options auto collection = db.create_collection( "capped_collection", options ); std::cout << "Capped collection '" << collection.name() << "' created with max size " << collection.options().max_size() << " bytes." << std::endl; return 0; } ``` -------------------------------- ### Create MongoDB Client Pool (Basic) Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/api/mongocxx/examples/clients.md Demonstrates the basic usage for creating a MongoDB client pool. ```cpp auto pool = mongocxx::client_pool{}; ``` -------------------------------- ### Custom Target: Doxygen Install Headers Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/CMakeLists.txt Configures a custom CMake target to install Doxygen headers. It clears the target directory and copies header files from source to the build directory. ```cmake add_custom_target(doxygen-install-headers VERBATIM # Clear any existing files in the target directory. COMMAND ${CMAKE_COMMAND} -E remove_directory ${MONGO_CXX_DRIVER_SOURCE_DIR}/build/doxygen/install # Manually "install" all headers without requiring compilation. COMMAND ${CMAKE_COMMAND} -E copy_directory ${MONGO_CXX_DRIVER_SOURCE_DIR}/src/bsoncxx/include ${MONGO_CXX_DRIVER_BINARY_DIR}/src/bsoncxx/lib ${MONGO_CXX_DRIVER_SOURCE_DIR}/build/doxygen/install/include COMMAND ${CMAKE_COMMAND} -E copy_directory ${MONGO_CXX_DRIVER_SOURCE_DIR}/src/mongocxx/include ${MONGO_CXX_DRIVER_BINARY_DIR}/src/mongocxx/lib ${MONGO_CXX_DRIVER_SOURCE_DIR}/build/doxygen/install/include ) ``` -------------------------------- ### List Database Names with Options Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/api/mongocxx/examples/clients.md Shows how to retrieve database names with specific options, such as filtering by name using a regular expression. ```cpp auto db_names = client.list_database_names(mongocxx::options::list_database_names{}); for (const auto& name : db_names) { // Process database name } ``` -------------------------------- ### Install pkg-config Package Config Files Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/src/mongocxx/cmake/CMakeLists.txt This function generates and installs pkg-config files for the MongoDB C++ driver. It handles different linking types (shared/static) and ABI versioning for pkg-config filenames. ```cmake function(mongocxx_install_pkg_config TARGET LINK_TYPE) get_target_property(output_name ${TARGET} OUTPUT_NAME) set(pcfilename "${CMAKE_CURRENT_BINARY_DIR}/lib${output_name}.pc") if (ENABLE_ABI_TAG_IN_PKGCONFIG_FILENAMES) if(LINK_TYPE STREQUAL "STATIC") get_target_property(bsoncxx_name bsoncxx_static OUTPUT_NAME) set(is_static 1) else() get_target_property(bsoncxx_name bsoncxx_shared OUTPUT_NAME) set(is_static 0) endif() else() if ("${BSONCXX_SOVERSION}" STREQUAL "_noabi") if(LINK_TYPE STREQUAL "STATIC") set(bsoncxx_name "$CACHE{BSONCXX_OUTPUT_BASENAME}-static") set(is_static 1) else() set(bsoncxx_name "$CACHE{BSONCXX_OUTPUT_BASENAME}") set(is_static 0) endif() else() if(LINK_TYPE STREQUAL "STATIC") set(bsoncxx_name "$CACHE{BSONCXX_OUTPUT_BASENAME}${BSONCXX_SOVERSION}-static") set(is_static 1) else() set(bsoncxx_name "$CACHE{BSONCXX_OUTPUT_BASENAME}${BSONCXX_SOVERSION}") set(is_static 0) endif() endif() endif() add_custom_command( OUTPUT ${pcfilename} COMMAND ${CMAKE_COMMAND} -D "src_dir=${CMAKE_CURRENT_SOURCE_DIR}" -D "bin_dir=${CMAKE_CURRENT_BINARY_DIR}" -D "prefix=${CMAKE_INSTALL_PREFIX}" -D "includedir=${CMAKE_INSTALL_INCLUDEDIR}" -D "libdir=${CMAKE_INSTALL_LIBDIR}" -D "output_name=${output_name}" -D "version=$CACHE{MONGOCXX_VERSION_NO_EXTRA}" -D "is_static=${is_static}" -D "bsoncxx_name=${bsoncxx_name}" -D "mongoc_req_ver=${MONGOC_REQUIRED_VERSION}" -P ${CMAKE_CURRENT_SOURCE_DIR}/generate-pc.cmake MAIN_DEPENDENCY ${CMAKE_CURRENT_SOURCE_DIR}/libmongocxx.pc.in DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/generate-pc.cmake ) add_custom_target(generate-lib${TARGET}-pc DEPENDS ${pcfilename}) add_dependencies(${TARGET} generate-lib${TARGET}-pc) if(ENABLE_ABI_TAG_IN_PKGCONFIG_FILENAMES) install(FILES ${pcfilename} DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) else() if("${MONGOCXX_SOVERSION}" STREQUAL "_noabi") if(is_static) set(pkgname "lib${MONGOCXX_OUTPUT_BASENAME}-static.pc") else() set(pkgname "lib${MONGOCXX_OUTPUT_BASENAME}.pc") endif() else() if(is_static) set(pkgname "lib${MONGOCXX_OUTPUT_BASENAME}${MONGOCXX_SOVERSION}-static.pc") else() set(pkgname "lib${MONGOCXX_OUTPUT_BASENAME}${MONGOCXX_SOVERSION}.pc") endif() endif() install( FILES ${pcfilename} DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig RENAME ${pkgname} ) endif() endfunction() if(MONGOCXX_BUILD_SHARED) mongocxx_install_pkg_config(mongocxx_shared SHARED) endif() if(MONGOCXX_BUILD_STATIC) mongocxx_install_pkg_config(mongocxx_static STATIC) endif() ``` -------------------------------- ### Initialize C++ Driver - Basic Usage Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/api/mongocxx/examples/instance.md Demonstrates the fundamental steps to initialize the MongoDB C++ driver. Ensure the driver is properly initialized before making any database operations. ```cpp #include #include #include int main() { // Initialize the MongoDB C++ driver mongocxx::instance instance{}; // The driver is now initialized and ready for use. // You can now create clients, databases, and collections. std::cout << "MongoDB C++ driver initialized successfully." << std::endl; return 0; } ``` -------------------------------- ### Install MongoDB C++ Driver Targets Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/src/mongocxx/cmake/CMakeLists.txt Installs the MongoDB C++ driver targets, including runtime libraries, development archives, and header files. This ensures the driver is available for use by other projects. ```cmake install( TARGETS ${mongocxx_target_list} EXPORT mongocxx_targets RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT runtime LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT runtime ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT dev INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/mongocxx/v_noabi ${CMAKE_INSTALL_INCLUDEDIR} ) ``` -------------------------------- ### Example Commit Message with JIRA Ticket Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/CONTRIBUTING.md Prefix your PR title with the JIRA ticket number for tracking. ```git CXX-XXXX Resolve an issue ``` -------------------------------- ### Create MongoDB URI - Basic Usage Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/api/mongocxx/examples/uri.md Demonstrates the basic construction of a MongoDB connection URI. ```cpp #include #include int main() { mongocxx::uri uri("mongodb://localhost:27017"); std::cout << "URI: " << uri.to_string() << std::endl; return 0; } ``` -------------------------------- ### Find libmongocxx with CMake Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/examples/projects/mongocxx/cmake/shared/CMakeLists.txt Use `find_package` to locate the mongocxx build. Ensure CMAKE_PREFIX_PATH is set to the installation directory of libmongocxx. ```cmake cmake_minimum_required(VERSION 3.15...4.99) project(HELLO_WORLD LANGUAGES C CXX) # Enforce the C++ standard, and disable extensions. if(NOT DEFINED CMAKE_CXX_STANDARD) set(CMAKE_CXX_STANDARD 11) endif() set(CMAKE_CXX_EXTENSIONS OFF) if (NOT CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Werror") endif() # NOTE: For this to work, the CMAKE_PREFIX_PATH variable must be set to point to the directory that # was used as the argument to CMAKE_INSTALL_PREFIX when building libmongocxx. find_package(mongocxx REQUIRED) add_executable(hello_mongocxx ../../hello_mongocxx.cpp) target_link_libraries(hello_mongocxx PRIVATE mongo::mongocxx_shared ) add_custom_target(run COMMAND hello_mongocxx DEPENDS hello_mongocxx WORKING_DIRECTORY ${CMAKE_PROJECT_DIR} ) # Sanity-check that static library macros are not set when building against the shared library. # Users don't need to include this section in their projects. get_target_property(LIBMONGOCXX_DEFINITIONS mongo::mongocxx_shared INTERFACE_COMPILE_DEFINITIONS) list(FIND LIBMONGOCXX_DEFINITIONS "BSONCXX_STATIC" LIST_IDX) if (${LIST_IDX} GREATER -1) message(FATAL_ERROR "Expected BSONCXX_STATIC to not be defined") endif() list(FIND LIBMONGOCXX_DEFINITIONS "MONGOCXX_STATIC" LIST_IDX) if (${LIST_IDX} GREATER -1) message(FATAL_ERROR "Expected MONGOCXX_STATIC to not be defined") endif() ``` -------------------------------- ### Create MongoDB Client with Custom URI Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/api/mongocxx/examples/clients.md Shows how to create a MongoDB client using a custom connection URI. ```cpp auto uri = mongocxx::uri{ "mongodb://localhost:27017" }; auto client = mongocxx::client{ uri }; ``` -------------------------------- ### Create an Index with Options using Index View Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/api/mongocxx/examples/collections.md Creates an index with specific options using the Index View. ```cpp #include #include #include #include #include #include #include int main() { mongocxx::instance instance{}; mongocxx::client client = mongocxx::client{}; mongocxx::database db = client["mydatabase"]; mongocxx::collection coll = db["mycollection"]; // Obtain an Index View mongocxx::index::view indexes = coll.indexes(); // Define the index key: ascending order on 'field1' using bsoncxx::builder::stream::key; auto key_builder = bsoncxx::builder::stream::document{}; key_builder << key("field1") << 1; // Define index options: unique index, created in background mongocxx::options::index index_options; index_options.unique(true); index_options.background(true); // Create the index with options indexes.create_one(std::move(key_builder), index_options); std::cout << "Unique index on 'field1' created in background using Index View." << std::endl; return 0; } ``` -------------------------------- ### Example Commit Message for Feature Implementation Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/CONTRIBUTING.md When implementing a feature that resolves multiple issues, list related JIRA tickets. ```git CXX-XXXX Implement a feature resolving several related issues * CXX-AAAA Commit A description * CXX-BBBB Commit B description * Additional commit description ``` -------------------------------- ### Project Directory Structure for C++ Driver Libraries Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/etc/coding_guidelines.md Illustrates the standard directory layout for the bsoncxx and mongocxx libraries, including include, lib, and test directories with versioned subdirectories for ABI management. ```text / ├── include// │ ├── docs/ │ ├── v_noabi// │ ├── v1/ │ └── ... ├── lib// │ ├── private/ │ ├── v_noabi// │ ├── v1/ │ └── ... ├── test/ │ ├── private/ │ ├── v_noabi/ │ ├── v1/ │ └── ... └── ... ``` -------------------------------- ### Build Local Documentation Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/etc/releasing.md Build both Hugo and Doxygen documentation locally using the 'docs' target. Optionally set the DOXYGEN_BINARY environment variable to specify a particular Doxygen executable. ```bash export DOXYGEN_BINARY= # Optional. For binary version compatibility. cmake --build build --target docs ``` -------------------------------- ### Generate Basic Package Version File Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/src/mongocxx/cmake/CMakeLists.txt Generates a `mongocxxConfigVersion.cmake` file using `write_basic_package_version_file`. This is typically used to define the version of the installed package. ```cmake write_basic_package_version_file( mongocxxConfigVersion.cmake VERSION $CACHE{MONGOCXX_VERSION} COMPATIBILITY SameMajorVersion ) ``` -------------------------------- ### Example Commit Message with Multiple JIRA Tickets Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/CONTRIBUTING.md When multiple JIRA tickets are related, they can be suffixed to the title or mentioned within the commit message. ```git Fix several related issues (CXX-AAAA, CXX-BBBB) * Commit A description * Commit B description * Commit C description ``` -------------------------------- ### Create MongoDB Client Pool with Client Options Source: https://github.com/mongodb/mongo-cxx-driver/blob/master/docs/api/mongocxx/examples/clients.md Shows how to create a MongoDB client pool with specific client options applied to all clients within the pool. ```cpp auto opts = mongocxx::options::client{}; opts.tls_options(mongocxx::options::tls_options{}); auto pool = mongocxx::client_pool{ opts }; ```