Search code examples
mongo-cxx-driver

mongo-cxx-driver can not iterate view


I have a mongodb collection with the following document:

{
    "_id" : ObjectId("5c879a2f277d8132d6707792"),
    "a" : "133",
    "b" : "daisy",
    "c" : "abc"
}

When I run the following mongocxx code:

auto r = client["DB"]["Collection"].find_one({}).value().view();
isREmpty = r.empty();
rLength = r.length();
isOneInR = r.begin() == r.end();

for (bsoncxx::document::element ele : r) {
    std::cout << "Got key" << std::endl;
}

I get isREmpty = false, rLength = 99, isOneInR = true and no output saying Got key.

I was expecting the print of "Got key" because one document returned from find_one.
Why isn't it showing?


Solution

  • You are viewing freed memory. The call to .value() creates a temporary bsoncxx::value object. You then get a view into that temporary object with .view() and attempt to examine the data, but it is too late.

    What you want to do instead is capture the cursor returned by find_one:

    auto cursor = client["DB"]["Collection"].find_one({});
    

    Please see the examples for more details, but here is a quick example: https://github.com/mongodb/mongo-cxx-driver/blob/master/examples/mongocxx/query.cpp#L43

    Lifetime management in the C++ driver requires attention. Please read the doc comments for the methods you use, as they will almost always describe the rules you must follow.