c++ bson插入更新怎样操作

   2024-09-30 6030
核心提示:在C++中,我们可以使用mongo-cxx-driver库来操作MongoDB数据库,包括插入和更新BSON文档首先,确保已经安装了mongo-cxx-driver库

在C++中,我们可以使用mongo-cxx-driver库来操作MongoDB数据库,包括插入和更新BSON文档

首先,确保已经安装了mongo-cxx-driver库。如果尚未安装,请参考官方文档进行安装:http://mongocxx.org/mongocxx-v3/installation/

接下来,编写一个简单的程序来演示如何插入和更新BSON文档:

#include<iostream>#include <bsoncxx/json.hpp>#include <mongocxx/client.hpp>#include <mongocxx/instance.hpp>#include <mongocxx/uri.hpp>int main() {    // 创建MongoDB实例    mongocxx::instance instance{};    // 连接到MongoDB    mongocxx::client client{mongocxx::uri{"mongodb://localhost:27017"}};    // 获取数据库和集合    auto db = client["my_database"];    auto coll = db["my_collection"];    // 创建一个BSON文档并插入    bsoncxx::document::value doc = bsoncxx::from_json(R"({ "name": "John", "age": 30 })");    auto res = coll.insert_one(doc.view());    std::cout << "Inserted document with id: "<< res->inserted_id().get_oid().value.to_string()<< std::endl;    // 更新BSON文档    bsoncxx::document::value filter = bsoncxx::builder::stream::document{} << "_id"<< res->inserted_id().get_oid() << bsoncxx::builder::stream::finalize;    bsoncxx::document::value update = bsoncxx::builder::stream::document{} << "$set" << bsoncxx::builder::stream::open_document << "age" << 31 << bsoncxx::builder::stream::close_document << bsoncxx::builder::stream::finalize;    auto update_res = coll.update_one(filter.view(), update.view());    std::cout << "Updated "<< update_res->modified_count() << " documents."<< std::endl;    return 0;}

这个程序首先创建了一个名为my_database的数据库和一个名为my_collection的集合。然后,它创建了一个包含name和age字段的BSON文档,并将其插入到集合中。最后,它更新了刚刚插入的文档,将age字段的值从30更改为31。

要编译此程序,请确保链接mongo-cxx-driver库。例如,使用g++编译器,可以使用以下命令:

g++ main.cpp -o main $(pkg-config --cflags --libs libmongocxx)

运行编译后的程序,您将看到类似以下的输出:

Inserted document with id: 5f8e9a74d6f8e9a74d6f8e9a74Updated 1 documents.

这表明已成功插入和更新BSON文档。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号