Linux下C++操作MongoDB

    科技2025-08-31  5

    其实主要就是参照官方文档 http://mongoc.org/libmongoc/current/installing.html

    一、安装驱动mongocxx-driver

    mongocxx依赖与mongo-c-driver,所以我们会先安装mongo-c-driver然后再安装mongo-cxx。

    1、安装mongo-c-driver

    #下载1.71.1版本的压缩包 wget https://github.com/mongodb/mongo-c-driver/releases/download/1.17.1/mongo-c-driver-1.17.1.tar.gz #解压压缩包 tar zxvf mongo-c-driver-1.17.1.tar.gz #进入目录 cd mongo-c-driver-1.17.1 mkdir cmake-build cd cmake-build cmake -DENABLE_AUTOMATIC_INIT_AND_CLEANUP=OFF .. make sudo make install

    卸载的话如下操作:

    sudo /usr/local/share/mongo-c-driver/uninstall.sh

    注意:这里安装mongo-c-driver的时候版本不能太低,否则后面安装mongo-cxx的时候会有如下报错。意思就是需要1.17.0以后的版本才可以。如果出现这种情况就卸载mongo-c-driver重新安装最新版本就好了。

    另外以上安装步骤其实在官方文档指引中都有,如下:http://mongoc.org/libmongoc/current/tutorial.html

     2、安装mongo-cxx

    #克隆cxx-driver文件夹 git clone https://github.com/mongodb/mongo-cxx-driver.git --branch releases/stable --depth 1 #进入build目录 cd mongo-cxx-driver/build cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local .. make && sudo make install

     

    二、测试mongodb

    1、实例一 ——新建一个库表并插入一条数据

    注:这个实例就是官方文档上的。其作用还有各种编译方法也都在指导文档中有。 更多操作参见 官方文档(是要重点研究的)

     (1)代码

    //hello_mongoc.c #include <mongoc/mongoc.h> int main (int argc, char *argv[]) { const char *uri_string = "mongodb://localhost:27017"; mongoc_uri_t *uri; mongoc_client_t *client; mongoc_database_t *database; mongoc_collection_t *collection; bson_t *command, reply, *insert; bson_error_t error; char *str; bool retval; /* * Required to initialize libmongoc's internals */ mongoc_init (); /* * Optionally get MongoDB URI from command line */ if (argc > 1) { uri_string = argv[1]; } /* * Safely create a MongoDB URI object from the given string */ uri = mongoc_uri_new_with_error (uri_string, &error); if (!uri) { fprintf (stderr, "failed to parse URI: %s\n" "error message: %s\n", uri_string, error.message); return EXIT_FAILURE; } /* * Create a new client instance */ client = mongoc_client_new_from_uri (uri); if (!client) { return EXIT_FAILURE; } /* * Register the application name so we can track it in the profile logs * on the server. This can also be done from the URI (see other examples). */ mongoc_client_set_appname (client, "connect-example"); /* * Get a handle on the database "db_name" and collection "coll_name" */ database = mongoc_client_get_database (client, "db_name"); collection = mongoc_client_get_collection (client, "db_name", "coll_name"); /* * Do work. This example pings the database, prints the result as JSON and * performs an insert */ command = BCON_NEW ("ping", BCON_INT32 (1)); retval = mongoc_client_command_simple ( client, "admin", command, NULL, &reply, &error); if (!retval) { fprintf (stderr, "%s\n", error.message); return EXIT_FAILURE; } str = bson_as_json (&reply, NULL); printf ("%s\n", str); insert = BCON_NEW ("hello", BCON_UTF8 ("world")); if (!mongoc_collection_insert_one (collection, insert, NULL, NULL, &error)) { fprintf (stderr, "%s\n", error.message); } bson_destroy (insert); bson_destroy (&reply); bson_destroy (command); bson_free (str); /* * Release our handles and clean up libmongoc */ mongoc_collection_destroy (collection); mongoc_database_destroy (database); mongoc_uri_destroy (uri); mongoc_client_destroy (client); mongoc_cleanup (); return EXIT_SUCCESS; }

    (2)编译:

    例如说此处手动指定头文件及包含路径进行编译,编译语句如下。执行后即可得到可执行文件。

    gcc -o hello_mongoc hello_mongoc.c \ -I/usr/local/include/libbson-1.0 -I/usr/local/include/libmongoc-1.0 \ -lmongoc-1.0 -lbson-1.0

    (3)执行

    执行的时候可能会报如下错误。意思很明显就是动态链接的时候在动态库路径下没找到要链接的东西。

    解决:

    ①首先看看我们的动态库搜索路径有哪些(记录在 /etc/ld.so.conf文件中)

    ②然后在安装路径下找到想要链接的这个so文件

    ③找到后再拷贝到上述任一个目录,例如 /usr/local/lib 中。这里把用到的都copy过去

    sudo cp -f mongo-cxx-driver/build/src/mongocxx/libmongocxx.so* /usr/local/lib sudo cp -f mongo-cxx-driver/build/src/bsoncxx/libbsoncxx.so* /usr/local/lib sudo cp ./mongo-c-driver-1.17.1/cmake-build/src/libmongoc/libmongoc-1.0.so* /usr/local/lib sudo cp ./mongo-c-driver-1.17.1/cmake-build/src/libbson/libbson-1.0.so * /usr/local/lib

    然后就可以执行了。

    ④执行效果。

           这段代码的作用就是创建一个名为db_name的库,然后再其下创建一个名为coll_name的表。然后往表里面插入了一条数据,执行效果如下:

     

     

    2、实例二 ——测试插入1000、10000条数据所需时间

    ①代码 

    #include <chrono> #include <bsoncxx/builder/basic/array.hpp> #include <bsoncxx/builder/basic/document.hpp> #include <bsoncxx/builder/basic/kvp.hpp> #include <bsoncxx/types.hpp> #include <mongocxx/client.hpp> #include <mongocxx/instance.hpp> #include <mongocxx/uri.hpp> #include<time.h> #include<string> #include<iostream> using bsoncxx::builder::basic::kvp; using bsoncxx::builder::basic::make_array; using bsoncxx::builder::basic::make_document; int main(int, char**) { mongocxx::instance inst{}; mongocxx::client conn{mongocxx::uri{}}; auto db = conn["test"]; // We choose to move in our document here, which transfers ownership to insert_one() clock_t startTime = clock(); for(int i = 0; i <= 1000; ++i) { bsoncxx::document::value restaurant_doc = make_document( kvp("address", make_document(kvp("street", "2 Avenue"), kvp("zipcode", 10075), kvp("building", "1480"), kvp("coord", make_array(-73.9557413, 40.7720266)))), kvp("borough", "Manhattan"), kvp("cuisine", "Italian"), kvp("grades", make_array( make_document(kvp("date", bsoncxx::types::b_date{std::chrono::milliseconds{12323}}), kvp("grade", "A"), kvp("score", 11)), make_document( kvp("date", bsoncxx::types::b_date{std::chrono::milliseconds{121212}}), kvp("grade", "B"), kvp("score", 17)))), kvp("name", "Vella"), kvp("restaurant_id", std::to_string(i))); auto res = db["restaurants"].insert_one(std::move(restaurant_doc)); } clock_t endTime = clock(); std::cout << " insert total time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " s" << std::endl; // @end: cpp-insert-a-document }

    ②编译

    c++ --std=c++11 mginsert.cpp -o mginsert $(pkg-config --cflags --libs libmongocxx) g++ mginsert.cpp -o mginsert $(pkg-config --cflags --libs libmongocxx)

    编译遇到如下问题:意思就是这些xxx.pc文件不再PKG_CONFIG_PATH 对应路径所以编译不通过。

    ③编译的问题与解决:

    1)首先看看 PKG_CONFIG_PATH 对应的路径是啥

    2)然后搜索xxx.pc文件的路径

    3)把xxx.pc文件复制过去

    sudo cp -f ./mongo-cxx-driver/build/src/mongocxx/config/libmongocxx.pc /usr/lib/pkgconfig/ sudo cp -f ./mongo-cxx-driver/build/src/bsoncxx/config/libbsoncxx.pc /usr/local/lib/pkgconfig/

    ④执行效果:

     

     

    Processed: 0.014, SQL: 8