Bulk.find.updateOne()

On this page本页内容

Tip

Starting in version 3.2, MongoDB also provides the db.collection.bulkWrite() method for performing bulk write operations.从3.2版开始,MongoDB还提供了db.collection.bulkWrite()方法来执行批量写入操作。

Description描述

Bulk.find.updateOne(<update>)

Adds a single document update operation to a bulk operations list.将单个文档更新操作添加到批量操作列表中。

Use the Bulk.find() method to specify the condition that determines which document to update. 使用Bulk.find()方法指定确定要更新哪个文档的条件。The Bulk.find.updateOne() method limits the update to a single document. Bulk.find.updateOne()方法将更新限制为单个文档。To update multiple documents, see Bulk.find.update().要更新多个文档,请参阅Bulk.find.update()

Bulk.find.updateOne() accepts the following parameter:接受以下参数:

Parameter参数Type类型Description描述
update document or pipeline文件或管道

The modifications to apply. 要应用的修改。Can be one of the following:可以是以下内容之一:

A replacement document替换文件

Contains only field and value pairs.仅包含字段和值对。

See also Bulk.find.replaceOne().另请参见Bulk.find.replaceOne()

Update document更新文档 Contains only update operator expressions.仅包含更新运算符表达式

Aggregation pipeline聚合管道

Starting in MongoDB 4.2从MongoDB 4.2开始

Contains only the following aggregation stages:仅包含以下聚合阶段:

For more information on the update modification parameter, see the db.collection.updateOne reference page.有关更新修改参数的更多信息,请参阅db.collection.updateOne参考页。

The sum of the associated <query> document from the Bulk.find() and the update document must be less than or equal to the maximum BSON document size.Bulk.find()中关联的<query>文档和更新文档的总和必须小于或等于最大BSON文档大小。

Behavior行为

If the <update> document contains only update operator expressions, as in:

{
  $set: { status: "D" },
  $inc: { points: 2 }
}

Then, Bulk.find.updateOne() updates only the corresponding fields, status and points, in the document.

Example示例

The following example initializes a Bulk() operations builder for the items collection, and adds various updateOne operations to the list of operations.

var bulk = db.items.initializeUnorderedBulkOp();
bulk.find( { status: "D" } ).updateOne( { $set: { status: "I", points: "0" } } );
bulk.execute();

Update with Aggregation Pipeline

Starting in version 4.2, update methods can accept an aggregation pipeline. For example, the following uses:

  • the $set stage which can provide similar behavior to the $set update operator expression,
  • the aggregation variable NOW, which resolves to the current datetime and can provide similar behavior to a $currentDate update operator expression. To access aggregation variables, prefix the variable with double dollar signs $$ and enclose in quotes.
var bulk = db.items.initializeUnorderedBulkOp();
bulk.find( {  status: "P" } ).updateOne(
   [
      { $set: { points: 0, lastModified: "$$NOW" } }
   ]
);
bulk.execute();