1

我正在尝试使用 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 数组进行过滤的查询的工作示例。

4

1 回答 1

2

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

顺便说一句,最好避开流构建器,因为在使用它时很容易遇到问题。都是正确使用流构建器的技巧的好例子。除了使用流构建器,您还可以使用基本构建器,它的实现要简单得多,并且如果您犯了错误,它会为您提供更明智的错误消息。

于 2017-05-05T17:45:26.647 回答