Compound Operations复合操作

Most database requests only need to read data out of a database or write data into a database. 大多数数据库请求只需要从数据库中读取数据或将数据写入数据库。However, client applications sometimes need to read and write data in a single interaction with the database.然而,客户机应用程序有时需要在与数据库的一次交互中读取和写入数据。

Compound operations combine read and write operations in a single atomic statement, so there's no chance of data changing in between a read and a subsequent write; in fact, both operations take place in the same line of code from the perspective of your client application.复合操作将读和写操作组合在一个原子语句中,因此在读和后续写之间不存在数据更改的机会;事实上,从客户端应用程序的角度来看,这两个操作都发生在同一行代码中。

This property can be useful in cases where you want to write to a specific document, but you haven't found it yet. 如果要写入特定文档,但尚未找到该文档,则此属性非常有用。If you just perform a read for the document's _id and then try to alter the document you just found, it's possible that someone else can alter the document in between your read and write operations. 如果您只是对文档的_id执行读取,然后尝试更改刚刚找到的文档,那么其他人可能会在您的读取和写入操作之间更改文档。This doesn't stop you from doing this work, but it can make error handling much more difficult. 这不会阻止您执行这项工作,但会使错误处理变得更加困难。Compound operations help keep your logic straightforward by handling that logic entirely inside the database behind a layer of abstraction, so you don't have to worry about it. 复合操作通过在抽象层后面完全在数据库内部处理逻辑来帮助保持逻辑的直观性,因此您不必担心它。While you can accomplish this task using separate reads and writes, doing so requires the client application to gracefully handle potential errors at any stage of the process and in multiple potential error states. 虽然可以使用单独的读写来完成此任务,但这样做需要客户机应用程序在流程的任何阶段以及在多个潜在错误状态下优雅地处理潜在错误。This increases the complexity of your code and can make your client application brittle and difficult to test.这会增加代码的复杂性,并会使客户端应用程序变得脆弱,难以测试。

There are three major compound operations:有三种主要的复合操作:

  • findOneAndDelete() matches multiple documents to a supplied query and removes the first of those matched documents.将多个文档与提供的查询匹配,并删除第一个匹配的文档。
  • findOneAndUpdate() matches multiple documents to a supplied query and updates the first of those matched documents using the provided update document.将多个文档与提供的查询匹配,并使用提供的更新文档更新第一个匹配的文档。
  • findOneAndReplace() matches multiple documents to a supplied query and replaces the first of those matched documents using the provided replacement document.将多个文档与提供的查询匹配,并使用提供的替换文档替换第一个匹配的文档。

All three methods accept an optional options object with configurable sort and projection options that work just like their read operation equivalents. 这三种方法都接受一个可选的options对象,该对象具有可配置的排序投影选项,其工作方式与它们的读取操作等价物相同。findOneAndUpdate() and findOneAndDelete() allow the client to configure the returnOriginal option, a boolean that determines if the method returns the pre-update or post-update version of the modified document.FindOneAndeDate()findOneAndDelete()允许客户端配置returnOriginal选项,这是一个布尔值,用于确定方法是否返回修改文档的更新前版本或更新后版本。