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