Database Manual / Reference / mongosh Methods / Bulk Operations

Mongo.bulkWrite() (mongosh method方法)

Definition定义

Mongo.bulkWrite(operations, options)

bulkWrite() performs multiple write operations across multiple databases and collections in a single call. 在单个调用中跨多个数据库和集合执行多个写入操作。This method replaces db.collection.bulkWrite(), which performs multiple write operations to a specific collection in a single call.此方法替换db.collection.bulkWrite(),后者在一次调用中对特定集合执行多个写入操作。

Note

You can only use Mongo.bulkWrite() with MongoDB 8.0 or later.您只能在MongoDB 8.0或更高版本中使用Mongo.bulkWrite()

Syntax语法

You can call bulkWrite() on the current Mongo() instance by using the following syntax:您可以使用以下语法在当前Mongo()实例上调用bulkWrite()

db.getMongo().bulkWrite(
[
{
namespace: "<db1.collection1>",
name: "insertOne",
document: { ... }
},
{
namespace: "<db2.collection2>",
name: "replaceOne",
filter: { ... }
}
],
{
ordered: boolean,
verboseResults: boolean,
bypassDocumentValidation: boolean,
let: Document
}
)

You can also call it on a different Mongo instance, like in the following example:您还可以在不同的Mongo实例上调用它,如下例所示:

const otherMongo = Mongo("<other connection string>");

otherMongo.bulkWrite([{ namespace: "<db.collection>", ... }]);

bulkWrite() accepts two parameters:接受两个参数:

Parameter参数Type类型Description描述
operationsArray of documents文档数组Defines an array of write operations. Each document in the array represents a write operation that you want to execute.定义一个写操作数组。数组中的每个文档都表示要执行的写入操作。
optionsDocument文档Defines options for the operation.定义操作的选项

A document in operations can represent one of six operations:operations中的文档可以表示六种操作之一:

  • insert one
  • replace one
  • update one
  • update many
  • delete one
  • delete many

The following sections describe the syntax you must use for documents that represent each operation.以下部分描述了表示每个操作的文档必须使用的语法。

Insert One插入一个

{
namespace: '<db.collection>',
name: 'insertOne',
document: Document
}
Field字段Type类型Description描述
namespaceString字符串The database and collection that you want to insert the document into.要将文档插入其中的数据库和集合。
nameString字符串The operation. Set to "insertOne" for an insert one operation.手术。设置为"insertOne"进行插入操作。
documentDocument文档The document that you want to insert.您要插入的文档。

Note

If you do not specify an _id field in the document to insert, mongosh automatically generates an _id.如果不在文档中指定要插入的_id字段,mongosh会自动生成_id

Update One or Many更新一个或多个

{
namespace: '<db>.<collection>',
name: 'updateOne' | 'updateMany',
filter: Document,
update: Document | Document[],
arrayFilters?: Document[],
hint?: Document | string,
collation?: Document,
upsert?: boolean
}
Field字段Type类型Description描述
namespaceString字符串The database and collection that you want to update documents in.要在其中更新文档的数据库和集合。
nameString字符串The operation. Set to "updateOne" for an update one operation. Set to "updateMany" for an update many operation.手术。设置为"updateOne"进行更新一条数据操作。设置为"updateMany"进行更新多条数据操作。
filterDocument文档The filter that matches one or more documents you want to update. During an update one operation, mongosh only updates the first matching document. During an update many operation, mongosh updates all documents that match the filter.与要更新的一个或多个文档匹配的筛选器。在update-one操作期间,mongosh只更新第一个匹配的文档。在更新多个操作期间,mongosh会更新所有与筛选器匹配的文档。
updateDocument文档The update to perform.要执行的更新。
arrayFiltersArray of documents文档数组(Optional) If you update an array-valued field, arrayFilters is a set of filters that specify which array elements an update applies to.(可选)如果更新数组值字段,arrayFilters是一组筛选器,用于指定更新应用于哪些数组元素。
hintDocument or string文档或字符串(Optional) The index to use for the operation.(可选)用于操作的索引
collationDocument文档(Optional) The collation to use when sorting results.(可选)排序结果时使用的排序规则
upsertBoolean布尔值Specifies whether MongoDB creates a new document if no document matches the filter. Defaults to false.指定如果没有文档与筛选器匹配,MongoDB是否创建新文档。默认为false

Replace One替换一个

{
namespace: '<db>.<collection>',
name: 'replaceOne',
filter: Document,
replacement: Document,
hint?: Document | string,
collation?: Document
}
Field字段Type类型Description描述
namespaceString字符串The database and collection that you want to replace documents in.要在其中替换文档的数据库和集合。
nameString字符串The operation. Set to "replaceOne" for a replace one operation.手术。设置为"replaceOne"进行更换一次操作。
filterDocument文档The filter that matches the document you want to update. During a replace one operation, mongosh only replaces the first matching document.与要更新的文档匹配的筛选器。在replace one操作中,mongosh只替换第一个匹配的文档。
replacementDocument文档The replacement document.替换文件。
hintDocument or string文档或字符串(Optional) The index to use for the operation.(可选)用于操作的索引
collationDocument文档(Optional) The collation to use when sorting results.(可选)排序结果时使用的排序规则

Delete One or Many删除一个或多个

{
namespace: '<db>.<collection>',
name: 'deleteOne' | 'deleteMany',
filter: Document,
hint?: Document | string,
collation?: Document
}
Field字段Type类型Description描述
namespaceString字符串The database and collection that you want to delete documents in.要在其中删除文档的数据库和集合。
nameString字符串The operation. Set to "deleteOne" for a delete one operation. Set to "deleteMany" for a delete many operation.手术。设置为"deleteOne"进行删除操作。设置为"deleteMany"进行删除多个操作。
filterDocument文档The filter that matches the document you want to delete. During a delete one operation, mongosh only deletes the first matching document. 与要删除的文档匹配的筛选器。在delete one操作中,mongosh只删除第一个匹配的文档。During a delete many operation, mongosh deletes all matching documents.在delete many操作中,mongosh会删除所有匹配的文档。
hintDocument or string文档或字符串(Optional) The index to use for the operation.(可选)用于操作的索引
collationDocument文档(Optional) The collation to use when sorting results.(可选)排序结果时使用的排序规则

Options选项

You can use the following options with bulkWrite(). You can pass a document to bulkWrite() that contains the options that you want to use. This document is optional.您可以在bulkWrite()中使用以下选项。您可以将包含要使用的选项的文档传递给bulkWrite()。此文档是可选的。

{
ordered?: boolean,
verboseResults?: boolean,
bypassDocumentValidation?: boolean,
let?: Document
}
Field字段Type类型Description描述
orderedBoolean布尔值(Optional) Indicates that MongoDB performs the bulk write in order of the documents that you provide. Defaults to true.(可选)表示MongoDB按照您提供的文档顺序执行批量写入。默认为true
verboseResultsBoolean布尔值(Optional) Specifies if bulkWrite() outputs verbose results. Defaults to false.(可选)指定bulkWrite()是否输出详细结果。默认为false
bypassDocumentValidationBoolean布尔值(Optional) Specifies if the write operation bypasses document validation rules. Defaults to false.(可选)指定写入操作是否绕过文档验证规则。默认为false
letDocument文档(Optional) Document of parameter names and values that you can access with aggregation variables.(可选)可以使用聚合变量访问的参数名称和值的文档。

Output输出

bulkWrite() returns an object with the following fields:返回一个包含以下字段的对象:

{
acknowledged: boolean,
insertedCount: int,
matchedCount: int,
modifiedCount: int,
deletedCount: int,
upsertedCount: int,
insertResults?: map(int, document),
updateResults?: map(int, document),
deleteResults?: map(int, document)
}
Field字段Type类型Description描述
acknowledgedboolean布尔值true if the server returns an acknowledgment, false otherwise.如果服务器返回确认,则为true,否则为false
insertedCountinteger整数Number of documents inserted.插入的文档数量。
matchedCountinteger整数Number of documents matched by filter.筛选器匹配的文档数。
modifiedCountinteger整数Number of documents modified.修改的文档数量。
deletedCountinteger整数Number of documents deleted.已删除的文档数量。
upsertedCountinteger整数Number of documents upserted.被打乱的文档数量。
insertResultsMap of integers to documents整数到文档的映射

Optional. 可选。Represents the results of each successful insert operation. Each operation is represented by an integer key, which contains a document with information corresponding to the operation. Document includes the following field:表示每次成功插入操作的结果。每个操作都由一个整数键表示,该键包含一个文档,其中包含与该操作对应的信息。文档包括以下字段:

  • insertedId: ObjectID. Represents the _id of the inserted document.:对象ID。表示插入文档的_id
updateResultsMap of integers to documents整数到文档的映射

Optional. 可选。Represents the results of each successful update operation. Each operation is represented by an integer key, which contains a document with information corresponding to the operation. Document includes the following fields:表示每次成功更新操作的结果。每个操作都由一个整数键表示,该键包含一个文档,其中包含与该操作对应的信息。文档包括以下字段:

  • matchedCount: integer. Represents the number of documents matched.:整数。表示匹配的文档数。
  • modifiedCount: integer. Represents the number of documents modified.:整数。表示修改的文档数。
  • upsertedId: ObjectID. Represents the _id of any upserted documents. Optional.:对象ID。表示任何被打乱的文档的_id。可选。
  • didUpsert: boolean. true if a document was upserted, false otherwise.:布尔值。如果文档被打乱,则为true,否则为false
deleteResultsMap of integers to documents整数到文档的映射

Optional. 可选。Represents the results of each successful delete operation. Each operation is represented by an integer key, which contains a document with information corresponding to the operation. Document includes the following field:表示每次成功删除操作的结果。每个操作都由一个整数键表示,该键包含一个文档,其中包含与该操作对应的信息。文档包括以下字段:

  • deletedCount: integer. Represents the number of documents deleted.:整数。表示已删除的文档数。

Examples示例

This example uses Mongo.bulkWrite() to perform the following operations in order:此示例使用Mongo.bulkWrite()按顺序执行以下操作:

  • inserts a document into the db.authors collection将文档插入到db.authors集合中
  • inserts a document into the db.books collection将文档插入db.books集合中
  • updates the previous document更新上一个文档
db.getMongo().bulkWrite(
[
{
namespace: 'db.authors',
name: 'insertOne',
document: { name: 'Stephen King' }
},
{
namespace: 'db.books',
name: 'insertOne',
document: { name: 'It' }
},
{
namespace: 'db.books',
name: 'updateOne',
filter: { name: 'it' },
update: { $set: { year: 1986 } }
}
],
{
ordered: true,
bypassDocumentValidation: true
}
)

mongosh performs the bulk write in order and returns the following document:按顺序执行批量写入并返回以下文档:

{
acknowledged: true,
insertedCount: 2,
matchedCount: 1,
modifiedCount: 1,
deletedCount: 0,
upsertedCount: 0,
insertResults: { '1': { insertedId: ObjectId('67ed8ce8efd926c84cab7945') },
'2': { insertedId: ObjectId('67ed8ce8efd926c84cab7946') } }
updateResults: { '1': { matchedCount: 1, modifiedCount: 1, didUpsert: false } }
}