Docs 菜单

批量写入操作

在本指南中,您可以学习;了解如何使用批量写入操作在单个数据库调用中执行多个写入操作。

考虑这样一种情况:您想要将一个文档插入到一个集合中,更新多个其他文档,然后删除一个文档。 如果使用单独的方法,则每个操作都需要调用自己的数据库。 相反,您可以使用批量操作来减少对数据库的调用次数。

本指南中的示例使用 Atlas示例数据集sample_restaurants数据库中的 restaurants集合。 要从PHP应用程序访问权限此集合,请实例化一个连接到Atlas 集群的MongoDB\Client ,并将以下值分配给$collection变量:

$collection = $client->sample_restaurants->restaurants;

要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅Atlas入门指南。

要运行批量写入操作,请将写入操作大量传递给MongoDB\Collection::bulkWrite()方法。 使用以下语法指定写入操作:

[
[ 'deleteMany' => [ $filter ] ],
[ 'deleteOne' => [ $filter ] ],
[ 'insertOne' => [ $document ] ],
[ 'replaceOne' => [ $filter, $replacement, $options ] ],
[ 'updateMany' => [ $filter, $update, $options ] ],
[ 'updateOne' => [ $filter, $update, $options ] ],
]

提示

有关删除、插入、替换和更新操作的更多信息,请参阅写入操作指南。

调用bulkWrite()方法时,库会按照大量中指定的顺序自动运行写入操作。 要学习;了解如何指示bulkWrite()以任意顺序运行写入操作,请参阅“修改批量写入行为”部分。

此示例对restaurants集合运行以下写入操作:

  • 用于插入name值为'Mongo's Deli'的文档的插入操作

  • 用于更新name值为'Mongo's Deli'的文档的cuisine字段的更新操作

  • 删除操作,用于删除borough值为'Manhattan'的所有文档

$result = $collection->bulkWrite(
[
[
'insertOne' => [
['name' => 'Mongo\'s Deli'],
['cuisine' => 'Sandwiches'],
['borough' => 'Manhattan'],
['restaurant_id' => '1234'],
],
],
[
'updateOne' => [
['name' => 'Mongo\'s Deli'],
['$set' => ['cuisine' => 'Sandwiches and Salads']],
],
],
[
'deleteMany' => [
['borough' => 'Manhattan'],
],
],
]
);

您可以通过传递指定选项值的大量作为参数来修改MongoDB\Collection::bulkWrite()方法的行为。 下表描述了可在大量中设立的选项:

选项
说明

bypassDocumentValidation

Specifies whether the operation bypasses document validation. This lets you modify documents that don't meet the schema validation requirements, if any exist. For more information about schema validation, see Schema Validation in the MongoDB Server manual.
Defaults to false.

codec

Sets the codec to use for encoding or decoding documents. Bulk writes use the codec for insertOne() and replaceOne() operations. For more information, see the Codecs guide.

writeConcern

Sets the write concern for the operation. For more information, see Write Concern in the MongoDB Server manual.

let

Specifies a document with a list of values to improve operation readability. Values must be constant or closed expressions that don't reference document fields. For more information, see the let statement in the MongoDB Server manual.

ordered

If set to true: when a single write fails, the operation stops without performing the remaining writes and throws an exception.
If set to false: when a single write fails, the operation continues to attempt the remaining write operations, if any, then throws an exception.
Defaults to true.

comment

Attaches a comment to the operation. For more information, see the insert command fields guide in the MongoDB Server manual.

session

Specifies the client session to associate with the operation.

以下示例调用bulkWrite()方法执行插入和删除操作,并将ordered选项设置为false

$result = $collection->bulkWrite(
[
[
'insertOne' => [
['name' => 'Mongo\'s Pizza'],
['cuisine' => 'Italian'],
['borough' => 'Queens'],
['restaurant_id' => '5678'],
],
],
[
'deleteOne' => [
['restaurant_id' => '5678'],
],
],
],
['ordered' => false]
);

如果库先运行插入操作,则会删除一个文档。 如果它先运行删除操作,则不会删除任何文档。

注意

无序批量操作不保证执行顺序。 为了优化运行时间,顺序可以与您列出的方式不同。

MongoDB\Collection::bulkWrite()方法返回一个MongoDB\BulkWriteResult对象。 该类包含以下成员函数:

function
说明

getDeletedCount()

Returns the number of documents deleted, if any.

getInsertedCount()

Returns the number of documents inserted, if any.

getInsertedIds()

Returns a map of _id field values for inserted documents, if any.

getMatchedCount()

Returns the number of documents matched during update and replace operations, if applicable.

getModifiedCount()

Returns the number of documents modified, if any.

getUpsertedCount()

Returns the number of documents upserted, if any.

getUpsertedIds()

Returns a map of _id field values for upserted documents, if any.

isAcknowledged()

Returns a boolean indicating whether the bulk operation was acknowledged.

要了解如何执行单个写入操作,请参阅以下指南:

要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: