mongodb - 何时在 mongodb cxx r3.0.2 驱动程序中使用 finalize

标签 mongodb mongodb-query mongo-cxx-driver

我很困惑,在 online doc, 的代码片段中它显示了调用 update_many 方法时 finalize 的用法,如下所示:

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);

但是我在没有finalize的mongocxx驱动代码中看到了示例代码

  // 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
    }

那么使用 finalize 和不使用它有什么区别呢?如何做出选择?

最佳答案

要了解这两种构造之间的区别,我们需要了解Owning BSON Documents (values) 之间的区别。和 Non-owning BSON Documents (views)通过深入研究源代码和 Working with BSON document documentation 中的页面.

拥有 BSON 文档,类型为 bsoncxx::document::value表示那些拥有其数据缓冲区的文档,因此当 value 超出范围时,他的缓冲区被释放。您可以了解scope here甚至better here如果它对你来说是新的。

finalize 从临时缓冲区返回 bsoncxx::document::value 类型的 BSON 文档。所以 finalize 返回一个 Owning BSON Document

另一方面,非拥有 BSON 文档bsoncxx::document::view 的实例; 拥有 BSON 文档的 View 。如文档中所述,

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.

也在 BSON Document lifetime 中用一个例子明确提到

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.

关于mongodb - 何时在 mongodb cxx r3.0.2 驱动程序中使用 finalize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40615872/

相关文章:

c++ - 文档{}的mongodb C++驱动程序编译错误

java - 路径 [] 上下文中 servlet [dispatcherServlet] 的 Servlet.service() 抛出异常 [处理程序调度失败;

node.js - 如何在没有 Mongoose 的情况下使用 express 连接到 mongodb?

mongodb - 我如何在 MongoDB 中按 $elemMatch 排序?

javascript - Node.js - 使用 console.log 显示 mongoDB 文档(无 Shell)

MongoDB 聚合组数组按日期

node.js - Mongoose 查询内部文档数组

c++ - 如何将 bsoncxx::document::element 写入控制台

mongodb - 在 Mongodb 中过滤数组内部的数组

c++ - Mongo C++ 驱动程序 - 如何更改超时配置