阅读量:74
在C++中,我们可以使用mongo-cxx-driver库来操作MongoDB数据库,包括插入和更新BSON文档
首先,确保已经安装了mongo-cxx-driver库。如果尚未安装,请参考官方文档进行安装:http://mongocxx.org/mongocxx-v3/installation/
接下来,编写一个简单的程序来演示如何插入和更新BSON文档:
#include
#include
#include
#include
#include
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 class="hljs-comment">// 更新BSON文档
bsoncxx::document::value filter = bsoncxx::builder::stream::document{} << "_id"<< res>inserted_id().get_oid() << bsoncxx xss=removed class="hljs-string">"$set" << bsoncxx class="hljs-string">"age" << 31 << bsoncxx class="hljs-keyword">auto update_res = coll.update_one(filter.view(), update.view());
std::cout << "Updated "<< update>modified_count() << " documents."<< std class="hljs-keyword">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: 5f8e9a74d6f8e9a74d6f8e9a74
Updated 1 documents.
这表明已成功插入和更新BSON文档。