Docs Menu
Docs Home
/ / /
C++ Driver
/

Replace Documents

On this page

  • Overview
  • Sample Data
  • Replace Operation
  • Replace One Document Example
  • Options
  • Return Value
  • Additional Information
  • API Documentation

In this guide, you can learn how to use the C++ driver to run a replace operation on a MongoDB collection. A replace operation removes all fields except the _id field in the target document and replaces them with new ones. You can call the replace_one() method to replace a single document.

The examples in this guide use the restaurants collection in the sample_restaurants database from the Atlas sample datasets. To access this collection from your C++ application, instantiate a mongocxx::client that connects to an Atlas cluster and assign the following values to your db and collection variables:

auto db = client["sample_restaurants"];
auto collection = db["restaurants"];

To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Get Started with Atlas guide.

You can perform a replace operation by calling the replace_one() method. This method removes all fields except the _id field from the first document that matches the search criteria. It then inserts the fields and values you specify into the document.

The replace_one() method requires the following parameters:

  • Query filter document: Specifies which document to replace. For more information about query filters, see Query Filter Documents in the MongoDB Server manual.

  • Replace document: Specifies the fields and values to insert in the new document.

Important

The values of _id fields are immutable. If your replacement document specifies a value for the _id field, it must match the _id value of the existing document.

The following example uses the replace_one() method to replace a document that has a name field value of "Nobu" with a new document that has a name field value of "La Bernadin":

auto query_filter = make_document(kvp("name", "Nobu"));
auto replace_doc = make_document(kvp("name", "La Bernadin"));
auto result = collection.replace_one(query_filter.view(), replace_doc.view());

To check if you successfully replaced the document, you can use the find_one() method to print out the new document:

auto new_doc = collection.find_one(make_document(kvp("name", "La Bernadin")));
std::cout << "New document: " << bsoncxx::to_json(*new_doc) << std::endl;
New document: { "_id" : { "$oid" : "..." }, "name" : "La Bernadin" }

To learn more about the find_one() method, see Find One Document in the Retrieve Data guide.

You can modify the behavior of the replace_one() method by passing an instance of the mongocxx::options::replace class as an optional argument. The following table describes the fields you can set in a mongocxx::options::replace instance:

Field
Description
bypass_document_validation
Specifies whether the replace operation bypasses document validation. When set to true, this lets you replace a document with a new document that doesn't meet the schema validation requirements. For more information, see Schema Validation in the MongoDB Server manual.
Defaults to false.
collation
Specifies the kind of language collation to use when sorting results. For more information, see Collation in the MongoDB Server manual.
comment
Specifies a comment of any valid BSON type to attach to the operation. Once set, this comment appears alongside records of this command in the following locations:
For more information, see the insert Command Fields guide in the MongoDB Server manual.
hint
Specifies the index to scan for documents that match the query filter. For more information, see the hint field in the MongoDB Server manual.
let
Specifies a document containing variables and their values to be used in the replace_one() method. This allows you to improve code readability by separating the variables from the operation text. Values must be constant or closed expressions that don't reference document fields. For more information, see the let field in the MongoDB Server manual.
upsert
Specifies whether the replace operation performs an upsert operation if no documents match the query filter.
Defaults to false.
write_concern
Sets the write concern for the operation. For more information, see Write Concern in the MongoDB Server manual.

The following example uses the create_index() method to create an ascending single-field index on the name field. It then passes a mongocxx::options::replace object to the replace_one() method after setting its hint field to the new index. This instructs the replace operation to search the name field index when replacing a document that has a name field value of "Nobu":

auto index_specification = make_document(kvp("name", 1));
collection.create_index(index_specification.view());
mongocxx::options::replace opts{};
opts.hint(mongocxx::hint{"name_1"});
auto query_filter = make_document(kvp("name", "Nobu"));
auto replace_doc = make_document(kvp("name", "La Bernadin"));
auto result = collection.replace_one(query_filter.view(), replace_doc.view(), opts);

To learn more about indexes, see the Optimize Queries with Indexes guide.

The following example passes a mongocxx::options::replace object to the replace_one() method after setting its upsert field value to true. Because no documents match the query filter, this instructs the replace operation to insert a new document with a name field value of "Shake Shack" into the collection:

std::cout << "Total document count before replace_one(): " << collection.count_documents({}) << std::endl;
mongocxx::options::replace opts{};
opts.upsert(true);
auto query_filter = make_document(kvp("name", "In-N-Out Burger"));
auto replace_doc = make_document(kvp("name", "Shake Shack"));
auto result = collection.replace_one(query_filter.view(), replace_doc.view(), opts);
std::cout << "Total document count after replace_one(): " << collection.count_documents({}) << std::endl;
Total document count before replace_one(): 25359
Total document count after replace_one(): 25360

The replace_one() method returns an instance of the mongocxx::result::replace class. This class contains the following member functions:

Function
Description
matched_count()
Returns the number of documents that matched the query filter, regardless of how many were replaced.
modified_count()
Returns number of documents modified by the replace operation. If a replaced document is identical to the original, it is not included in this count.
result()
Returns the bulk write result for the operation.
upserted_id()
Returns the ID of the document that was upserted in the database, if the driver performed an upsert.

The following example uses the replace_one() method to replace a document that has a name field value of "Shake Shack" with a new document that has a name field value of "In-N-Out Burger". It then calls the matched_count() member function to print the number of documents that match the query filter:

auto query_filter = make_document(kvp("name", "Shake Shack"));
auto replace_doc = make_document(kvp("name", "In-N-Out Burger"));
auto result = collection.replace_one(query_filter.view(), replace_doc.view());
std::cout << "Matched documents: " << result->matched_count() << std::endl;
Matched documents: 11

The following example uses the replace_one() method to replace a document that has a name field value of "In-N-Out Burger". Because the upsert option is set to true, the C++ driver inserts a new document when the query filter doesn't match any existing documents. Then, the code calls the upserted_id() member function to print the _id field value of the upserted document:

mongocxx::options::replace opts{};
opts.upsert(true);
auto query_filter = make_document(kvp("name", "In-N-Out Burger"));
auto replace_doc = make_document(kvp("name", "Shake Shack"));
auto result = collection.replace_one(query_filter.view(), replace_doc.view(), opts);
auto id = result->upserted_id()->get_value();
std::cout << "Upserted ID: " << id.get_oid().value.to_string() << std::endl;
// Your ID value may differ
Upserted ID: 67128c5ecc1f8c15ea26fcf8

To learn more about creating query filters, see the Specify a Query guide.

To learn more about any of the methods or types discussed in this guide, see the following API documentation:

Back

Update