mongocxx: how to add upsert option to collection.update

1,025 views
Skip to first unread message

Per Bjarne Bro

unread,
Apr 20, 2017, 7:58:39 PM4/20/17
to mongodb-user
Hello,

I am using release 3.1.1 of the mongocxx driver with the streaming interface. I would like to update a collection with the upsert option to insert a document if not found. Currently, the following command will update a document correctly, however, I don't know how to add the upsert option to the update_one function, or to set upsert=true as default for the socioCollection collection.


socioCollection.update_one(document{} <<
                    "RUT" << rutStr << finalize,
                    document{} << "$set" << open_document <<
                    "Nombres" << nomStr <<
                    "Apellidos" << apeStr <<
                    "Sector" << secStr <<
                    "categoria" << catStr <<
                    "telefono" << telStr <<
                    "correo" << corStr <<
                    close_document << finalize);

//                  .upsert(true);
//                  mongocxx::options::update_one::upsert(true)
//                  update_one& mongocxx::options::update_one::upsert(true)
//                  );


Rassi

unread,
Apr 21, 2017, 6:09:51 AM4/21/17
to mongodb-user
Hi there,

To do this, you need to pass collection::update_one() a const reference to a mongocxx::options::update_one object as the third argument, where the upsert option is set to true on the options object.  See this excerpt from the mongocxx tests for an example: https://github.com/mongodb/mongo-cxx-driver/blob/r3.1.1/src/mongocxx/test/collection.cpp#L451-L454.

Collections don't have default update options, so it's not possible to set the default for the collection.

~ rassi
Reply all
Reply to author
Forward
0 new messages