MongoDB c++ driver(六)

本文介绍如何使用MongoDB的C++驱动程序进行查找操作。通过编译并运行示例代码`3find3.cpp`,演示了利用`libmongocxx`库进行查询的步骤。
摘要由CSDN通过智能技术生成

MongoDB c++ driver(六)

查找实现(三)

#include <iostream>

#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>

#include <mongocxx/client.hpp>
#include <mongocxx/options/find.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>

using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::open_document;
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::open_array;
using bsoncxx::builder::stream::close_array;
using bsoncxx::builder::stream::finalize;

int main(int argc, char** args)
{
    mongocxx::instance inst{};
    //chenzw:123 -->用户:密码  参考博客用户管理
    mongocxx::client conn{mongocxx::uri{"mongodb://chenzw:123@IP:端口号"}};

    auto db = conn["guanwang"];

    //找address子文档下zipcode:10075的文档
    bsoncxx::builder::stream::document filter_builder;
    filter_builder << "address.zipcode" << "10075";

    auto cursor = db["restaurants"].find(filter_builder.view());
    for (auto&& doc : cursor) {
            std::cout << bsoncxx::to_json(doc) << std::endl;
    }

    std::cout << "\n\n----------------------------------\n\n" << std::endl;
    //找grades数组中grade:'B'的文档
    //bsoncxx::builder::stream::document filter_builder;
    filter_builder.clear();    //没有这句的话会与前面的筛选条件相与!!!
    filter_builder << "grades.grade"<< "B";

    cursor = db["restaurants"].find(filter_builder.view());
    for (auto&& doc : cursor) {
            std::cout << bsoncxx::to_json(doc) << std::endl;
    }


    return 0;
}

编译、运行

$ c++ –std=c++11 3find3.cpp -o 3find3 $(pkg-config –cflags –libs libmongocxx)

$ ./3find3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值