Unset Document :: element,MongoCXX Find Option Projection

时间:2016-03-09 08:25:57

标签: mongodb mongo-cxx-driver

以下是尝试将mongo查询与项目查找选项一起使用的代码。

for (i in 1:3) {
      assign(eval(paste0("v", i)), X[i,i])
   }

没有“opts”的上述查询可以正常工作,而带有“opts”的查询会引发以下错误。

    using bsoncxx::builder::stream::document;
    mongocxx::options::find opts;
    document condition, options;

    const static int readdomain = 90000;

    condition << "lastRead" << open_document << "$gte" << readdomain << close_document;
    options << "read" << 1;
    opts.projection(options.view());
    mongocxx::cursor cursor = collection.find(condition.view(), opts);

1 个答案:

答案 0 :(得分:0)

当我尝试从完全没有这些键的文档中获取键值时,它将引发[what():unset document :: element]。

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

    mongocxx::instance inst{};
    mongocxx::client conn{mongocxx::uri{"mongodb://10.9.0.1:27017"}};
    mongocxx::collection collection = conn["wechat"]["article"];

    mongocxx::options::find opts;
    mongocxx::options::count copts;
    document condition, options;

    condition << "$and" << open_array <<
            open_document << "subscribeRobot" << open_document << "$exists" << 1 << close_document << close_document <<
            open_document << "body.title" << open_document << "$exists" << 1 << close_document << close_document <<
            open_document << "body.content" << open_document << "$exists" << 1 << close_document << close_document <<
            close_array;

    options << "subscribeRobot" << 1 << "body.title" << 1 << "body.content" << 1;
    opts.projection(options.view());
    copts.limit(1000);

    mongocxx::cursor cursor = collection.find(condition.view(), opts);
    dociter docbegin = cursor.begin();
    int64_t allartnumber = collection.count(condition.view(), copts);
    cout << allartnumber << endl;

    # pragma omp parallel for
    for(int i = 0; i < allartnumber; i++){
        doc = *(next(docbegin, i));
        wechat = bsoncxx::to_json(doc["subscribeRobot"]);
        title = bsoncxx::to_json(doc["body"]["title"]);
        // It will raise [what():  unset document::element] when these key above don't exists.
    }