Qt使用MongoDB的c++接口:连接、创建、写入、读取
    		       		warning:
    		            这篇文章距离上次修改已过427天,其中的内容可能已经有所变动。
    		        
        		                
                
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
#include <iostream>
 
int main() {
    mongocxx::instance inst{};         // 初始化MongoDB C++驱动
    mongocxx::client conn{mongocxx::uri{}}; // 创建客户端连接
 
    // 检查是否连接成功
    if (conn) {
        std::cout << "Connected to MongoDB!" << std::endl;
 
        // 获取数据库和集合
        auto db = conn["testdb"];
        auto collection = db["testcollection"];
 
        // 插入文档
        collection.insert_one({{"hello", "world"}});
 
        // 查询文档
        auto cursor = collection.find({});
        for (auto doc : cursor) {
            std::cout << bsoncxx::to_json(doc) << std::endl;
        }
    } else {
        std::cout << "Failed to connect to MongoDB!" << std::endl;
    }
 
    return 0;
}这段代码展示了如何使用mongocxx库在Qt中连接到MongoDB,创建数据库和集合,插入一个文档,并且查询所有文档。在实际应用中,你需要确保已经安装了mongocxx库,并且在你的项目文件(.pro)中正确地添加了相关的库引用。
评论已关闭