2017-05-03 51 views
0

我想使用mongocxx驱动程序为C++填充查询。发现中的ObjectID的Mongocxx数组

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数组进行过滤的查询的工作示例。

回答

2

要构建一个数组,您需要使用数组构建器,而不是文档构建器。该阵列的生成器声明应为bsoncxx::builder::stream::array unit_filter_builder。它也看起来像你错过了各种流构建器类型的几个包含。另外,最好避开流生成器,因为在使用它时很容易遇到问题。 Thisthis是正确使用流构建器的巧妙例子。您可以使用基本构建器,而不是使用流构建器,它具有更简单的实现,并且如果您犯了一个错误,则会提供更详细的错误消息。

+0

谢谢!我会看看 – ppaulojr