bsoncxx and field values

6 views
Skip to first unread message

Jeff Abrahamson

unread,
Nov 16, 2017, 2:43:40 PM11/16/17
to mongodb-user
I'm a bit confused by the docs (and examples and code) about how to extract values from bson.  It looks to me like something like this ought to work, although [] returns a document::element and key() converts that to a string_view, and none of these things are the actual types I want.

​    mongocxx::collection collection = db["my_collection"];
    mongocxx::cursor cursor =
        collection.find(document{}
            << "my_id" << open_document << "$gt" << 285
            << close_document << finalize);
    for (auto doc : cursor) {
        // I expect the field _id to be an oid.
        cout << doc["_id"].key() << "    ";
        // I expect the field my_id to be an integer.
        cout << doc["my_id"].key() << "    ";
        // I expect the field animal to be a string.
        cout << doc["animal"].key() << endl;
    }​

At another point in the docs, I feared I had to things like this, which reassuringly is wrong:

    bsoncxx::to_json(document::element(doc["animal"]).get_value())

The compiler kindly gives me type errors, which lead me to interfaces to try, but I'm missing something.  Any pointers?

Jeff Abrahamson

unread,
Nov 16, 2017, 2:50:33 PM11/16/17
to mongodb-user
I'll just go on anwering my own questions today..

    cout << doc["_id"].get_oid().value.to_string() << "    "
         << doc["my_id"].get_int32().value.to_string() << endl;
         << doc["animal"].get_utf8().value.to_string() << endl;


Jeff Abrahamson
https://p27.eu/jeff/

Reply all
Reply to author
Forward
0 new messages