【问题标题】:Mongocxx array of ObjectID in find查找中的 ObjectID 的 Mongocxx 数组
【发布时间】:2017-05-03 21:13:22
【问题描述】:

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

【问题讨论】:

    标签: mongodb mongo-cxx-driver


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-04-30
      • 2019-05-07
      • 2017-04-20
      相关资源
      最近更新 更多