I am confused, in code snippets of online doc, it shows the usage of finalize when calling update_many method, like so:
mongocxx::stdx::optional<mongocxx::result::update> result =
collection.update_many(
document{} << "i" << open_document <<
"$lt" << 100 << close_document << finalize,
document{} << "$inc" << open_document <<
"i" << 100 << close_document << finalize);
But I have seen the example code in mongocxx driver code without finalize
// Update multiple documents.
{
// @begin: cpp-update-multiple-documents
bsoncxx::builder::stream::document filter_builder, update_builder;
filter_builder << "address.zipcode"
<< "10016"
<< "cuisine"
<< "Other";
update_builder << "$set" << open_document << "cuisine"
<< "Category To Be Determined" << close_document << "$currentDate"
<< open_document << "lastModified" << true << close_document;
db["restaurants"].update_many(filter_builder.view(), update_builder.view());
// @end: cpp-update-multiple-documents
}
So what difference between using finalize or not using it? How to make a choice?
To understand the difference between the two construct, we need to understand the difference between Owning BSON Documents (values) and Non-owning BSON Documents (views) by diving into the source code and the Working with BSON document page in the documentation.
Owning BSON Documents which type is bsoncxx::document::value
represent those documents that own their buffer of data so when the value goes out of scope, his buffer is freed. You can learn about scope here or even better here if it is new to you.
finalize
returns a BSON document of type bsoncxx::document::value
from a temporary buffer. So finalize
returns an Owning BSON Document.
On the other hand, Non-owning BSON Documents are instance of bsoncxx::document::view
; a view into an Owning BSON Document. And as mentioned in the documentation,
In performance-critical code, passing views around is preferable to using values because we can avoid excess copying. Also, passing a view of a document allows us to use the document multiple times.
Also in the BSON Document lifetime explicitly mentioned with an example that
It is imperative that
document::values
outlive anydocument::views
that use them. If the underlying value gets cleaned up, the view will be left with a dangling pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With