MongoDB C++ Driver API 官方文档链接
在mongo-cxx-driver/examples文件夹下,有bsoncxx和mongocxx两个代码文件夹,对应于这两个命名空间。
1. bsoncxx
文件夹下包含的cpp
对应于API中的
从实用的角度讲,通过代码分析用法更为有效。
关于bsoncxx::builder
中的basic
,stream
和core
builder_core.cpp中有这样一句注释
// bsoncxx::builder::core is a low-level primitive that can be useful for building other
// BSON abstractions. Most users should just use builder::stream or builder::basic.
而我自己觉得,builder::basic
也是一种比较传统的创建builder::basic::document{}
文档的方式,如果创建比较复杂的文档,还是太繁琐了,所以实用builder::stream
流式的方式比较好。
现选择builder_stream.cpp和getting_values.cpp进行分析:
1.1 流式构造文档
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/builder/stream/array.hpp>
#include <bsoncxx/builder/stream/helpers.hpp>
#include <bsoncxx/types.hpp>
using namespace bsoncxx;
int main(int, char**) {
using builder::stream::document;
using builder::stream::array;
// bsoncxx::builder::stream presents an iostream like interface for succintly
// constructing complex BSON objects.
// stream::document builds a BSON document 构造一个BSON文档
auto doc = document{};
// stream::array builds a BSON array 构造一个BSON数组
auto arr = array{};
// We append keys and values to documents using the '<<' operator;使用<<运算符
// 连接key和value
doc << "myKey"
<< "myValue