查找中的 ObjectID 的 Mongocxx 数组

Mongocxx array of ObjectID in find

我正在尝试使用 mongocxx 驱动程序为 C++ 填充查询。

Javascript 中的查询如下:

{unit_id: {$in: [ObjectId('58aee90fefb6f7d46d26de72'),
                ObjectId('58aee90fefb6f7d46d26de73']
          }
}

我在想下面的代码可以生成数组部分,但它不能编译。

#include <cstdint>
#include <iostream>
#include <vector>
#include <bsoncxx/json.hpp>
#include <bsoncxx/types.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/stdx.hpp>
#include <mongocxx/uri.hpp>
#include <mongocxx/instance.hpp>

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

mongocxx::instance instance {};
mongocxx::client client{mongocxx::uri{}};
mongocxx::database db = client["banff_development"];
mongocxx::collection coll = db["units"];

int main()
{
    mongocxx::cursor cursor = coll.find
 (document{} << "provider_id" << bsoncxx::oid("58aee90fefb6f7d46d26de4a") 
 <<  finalize);
    bsoncxx::builder::stream::document unit_filter_builder;
    for (auto a: cursor)
    {
        unit_filter_builder << a["_id"].get_oid();
    }
    return 0;
}

在哪里可以找到使用 ObjectId 数组进行过滤的查询的工作示例。

要构建数组,您需要使用数组生成器,而不是文档生成器。数组生成器的声明应为 bsoncxx::builder::stream::array unit_filter_builder。看起来您还缺少针对各种流生成器类型的几个包含。

顺便说一句,最好避开流生成器,因为使用它时很容易 运行 遇到问题。 and this 是正确使用流生成器的技巧的好例子。您可以使用基本构建器来代替流构建器,它的实现要简单得多,并且在您犯错时会给出更清晰的错误消息。