Search code examples
c++mongodbmongo-cxx-driver

How to set a value in a document in mongocxx find_one_and_update


I hae a query to find one and update a document in my collection. The issue is, when I do so, the document is made empty instead of updated. Here's my code:

auto collection = db["cities"];

bsoncxx::builder::stream::document query{};
query << "Address" << std::getenv("TESTADDRESS");

bsoncxx::builder::stream::document update{};
update << "verified" << true;

auto serverQuery = collection.find_one_and_update(query.view(), update.view());

if( serverQuery ) {
    //Do something
}

What do I have to do with the update document to make it so that it updates fields. When I use the query's view in place of the update view, I get the same document without it being emptied. Only when using the update document is when I get a blank document (only the "_id" field remains).


Solution

  • To update a field like that you need to use the operator $set:

    update << "$set" << bsoncxx::builder::stream::open_document <<
                        "verified" << true <<
                        bsoncxx::builder::stream::close_document;
    

    And to return the modified document remember to use the returnNewDocument option of findOneAndUpdate.

    More info in MongoDb site about update operators.