[CXX-925] How to upsert a replace_one in C++11 driver? Created: 08/Jun/16  Updated: 11/Sep/19  Resolved: 13/Jun/16

Status: Closed
Project: C++ Driver
Component/s: Implementation
Affects Version/s: 3.0.1
Fix Version/s: None

Type: Task Priority: Trivial - P5
Reporter: George Thompson Assignee: Unassigned
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Windows 10
MS VS 2015
MongoDB 3.3.5
MongoDB C++11 Driver 3.0.1


Issue Links:
Duplicate

 Description   

According to the update tutorial to replace one:

db[this->id()].replace_one(filter_builder.view(), bsb_file_blueprint.view());

It goes on to state:

By specifying the upsert option to true, the update operation either updates matching document(s) or inserts a new document if no matching document exists.

referring me to the C++11 documentation but without an example.

I have (using the bulk_write.cpp example):

{{mongocxx::model::replace_one upsert_op(filter_builder.view(), bsb_file_blueprint.view());
upsert_op.upsert(true);}}

But I'm unsure what to do next. Am I to do a bulk_write? Is there an easier way?



 Comments   
Comment by George Thompson [ 09/Jun/16 ]

Thank you Andrew. I was focusing on the mongocxx::model::replace_one linked from the tutorial when, naturally, I should have been focusing on mongocxx::collection class. I have an entire tab group dedicated to the c+11 classes and I should have caught that easily.

Possibly the tutorial should point to the collection class vs. model?

Thanks as always.

Comment by Andrew Morrow (Inactive) [ 08/Jun/16 ]

There are two ways to do what you want:

  • You can create an instance of mongocxx::model::replace_one, with the filter, replacement, and upsert flag set as you want, wrap the replace_one object up in a mongocxx::bulk_write object, and then use collection::bulk_write to issue it.
  • You can use mongocxx::collection::replace_one, passing the filter and replacement as arguments, along with a mongocxx::options::update object with the upsert flag set as you want.

In fact, the latter method is just shorthand for the first. You may find looking at the implementation of mongocxx::collection::replace_one helpful:

https://github.com/mongodb/mongo-cxx-driver/blob/d20926ba607e110b7fd699e1cfe0e3ddcfa0bf01/src/mongocxx/collection.cpp#L353-L376

Generated at Wed Feb 07 22:00:48 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.