Mongocxx array of ObjectID in find

折月煮酒 提交于 2021-01-28 07:38:35

问题


I'm trying to populate a query for a C++ using mongocxx driver.

The query in Javascript would be like:

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

I was thinking that the following code could work to generate the array part, but it doesn't compile.

#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;
}

Where can I find an working example for queries using ObjectId arrays to filter.


回答1:


To build an array, you need to use the array builder, not the document builder. The declaration of the builder for the array should be bsoncxx::builder::stream::array unit_filter_builder. It also looks like you're missing a couple of includes for the various stream builder types.

As an aside, it's better to shy away from the stream builder, as it's very easy to run into issues when using it. This and this are good examples of the trickiness of using the stream builder properly. Instead of using the stream builder, you can use the basic builder, which has a much simpler implementation and gives you much saner error messages if you make a mistake.



来源:https://stackoverflow.com/questions/43770113/mongocxx-array-of-objectid-in-find

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!