Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when to use finalize in mongodb cxx r3.0.2 driver

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?

like image 527
Dean Chen Avatar asked Nov 09 '22 06:11

Dean Chen


1 Answers

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 any document::views that use them. If the underlying value gets cleaned up, the view will be left with a dangling pointer.

like image 144
styvane Avatar answered Nov 15 '22 05:11

styvane