db.collection.insertMany()
On this page本页内容
Definition定义
db.collection.insertMany()
- Important
mongosh Method
This page documents a
mongosh
method. This is not the documentation for database commands or language-specific drivers, such as Node.js.For the database command, see the
insert
command.For MongoDB API drivers, refer to the language-specific MongoDB driver documentation.
For the legacy
mongo
shell documentation, refer to the documentation for the corresponding MongoDB Server release:Inserts multiple documents into a collection.在集合中插入多个文档。TheinsertMany()
method has the following syntax:insertMany()
方法具有以下语法:db.collection.insertMany(
[ <document 1> , <document 2>, ... ],
{
writeConcern: <document>,
ordered: <boolean>
}
)Parameter参数Type类型Description描述document
document An array of documents to insert into the collection.要插入到集合中的文档数组。writeConcern
document Optional.可选的。A document expressing the write concern. Omit to use the default write concern.表示写入关注的文件。忽略使用默认的写入关注。
Do not explicitly set the write concern for the operation if run in a transaction.如果在事务中运行,请不要显式设置操作的写入关注。To use write concern with transactions, see Transactions and Write Concern.要在事务中使用写入关注,请参阅事务和写入关注。ordered
boolean Optional.可选的。A boolean specifying whether the一个布尔值,指定mongod
instance should perform an ordered or unordered insert.mongod
实例应该执行有序插入还是无序插入。Defaults to默认为true
.true
。Returns:返回值:A document containing:包含以下内容的文档:An一个acknowledged
boolean, set totrue
if the operation ran with write concern orfalse
if write concern was disabledacknowledged
布尔值,如果运行操作时存在写入关注,则设置为true
;如果禁用写入关注,设置为false
AninsertedIds
array, containing_id
values for each successfully inserted documentinsertedIds
数组,包含每个成功插入的文档的_id
值
Behaviors行为
Given an array of documents, 给定一个文档数组,insertMany()
inserts each document in the array into the collection.insertMany()
将数组中的每个文档插入到集合中。
Execution of Operations操作的执行
By default, documents are inserted in the order they are provided.默认情况下,文档是按照提供的顺序插入的。
If 如果ordered
is set to true
and an insert fails, the server does not continue inserting records.ordered
设置为true
并且插入失败,则服务器不会继续插入记录。
If 如果ordered
is set to false
and an insert fails, the server continues inserting records. ordered
设置为false
并且插入失败,则服务器将继续插入记录。Documents may be reordered by mongod
to increase performance. mongod
可以重新排序文档以提高性能。Applications should not depend on ordering of inserts if using an unordered 如果使用无序的insertMany()
.insertMany()
,则应用程序不应依赖于插入的顺序。
The number of operations in each group cannot exceed the value of the maxWriteBatchSize of the database. 每个组中的操作数不能超过数据库的maxWriteBatchSize
值。The default value of maxWriteBatchSize
is 100,000
. maxWriteBatchSize
的默认值为100000
。This value is shown in the 该值显示在hello.maxWriteBatchSize
field.hello.maxWriteBatchSize
字段中。
This limit prevents issues with oversized error messages. 此限制可防止出现错误消息过大的问题。If a group exceeds this limit, the client driver divides the group into smaller groups with counts less than or equal to the value of the limit. 如果一个组超过此限制,客户端驱动程序会将该组划分为计数小于或等于限制值的较小组。For example, with the 例如,当maxWriteBatchSize
value of 100,000
, if the queue consists of 200,000
operations, the driver creates 2 groups, each with 100,000
operations.maxWriteBatchSize
值为100000
时,如果队列由200000
个操作组成,则驱动程序将创建两个组,每个组包含100000
个操作。
The driver only divides the group into smaller groups when using the high-level API. 当使用高级API时,驱动程序仅将组划分为较小的组。If using 如果直接使用db.runCommand()
directly (for example, when writing a driver), MongoDB throws an error when attempting to execute a write batch which exceeds the limit.db.runCommand()
(例如,在编写驱动程序时),MongoDB在尝试执行超过限制的写批时会抛出错误。
If the error report for a single batch grows too large, MongoDB truncates all remaining error messages to the empty string. 如果单个批次的错误报告过大,MongoDB会将所有剩余的错误消息截断为空字符串。If there are at least two error messages with total size greater than 如果至少有两条错误消息的总大小大于1MB
, they are trucated.1MB
,则对它们进行trucated。
The sizes and grouping mechanics are internal performance details and are subject to change in future versions.尺寸和分组机制是内部性能细节,在未来版本中可能会发生变化。
Executing an 在分片集合上执行有序操作列表通常比执行无序列表慢,因为对于有序列表,每个操作都必须等待上一个操作完成。ordered
list of operations on a sharded collection will generally be slower than executing an unordered
list since with an ordered list, each operation must wait for the previous operation to finish.
Collection Creation集合创建
If the collection does not exist, then 如果集合不存在,那么insertMany()
creates the collection on successful write.insertMany()
会在成功写入时创建集合。
_id
Field字段
If the document does not specify an _id field, then 如果文档没有指定mongod
adds the _id
field and assign a unique ObjectId()
for the document. _id
字段,那么mongod
会添加_id
字段并为文档分配一个唯一的ObjectId()
。Most drivers create an ObjectId and insert the 大多数驱动程序创建一个_id
field, but the mongod
will create and populate the _id
if the driver or application does not.ObjectId
并插入_id
字段,但如果驱动程序或应用程序没有创建并填充_id
,mongod
将创建并填充。
If the document contains an 如果文档包含_id
field, the _id
value must be unique within the collection to avoid duplicate key error._id
字段,则_id
值在集合中必须是唯一的,以避免重复的键错误。
Explainability解释能力
insertMany()
is not compatible with 与db.collection.explain()
.db.collection.explain()
不兼容。
Error Handling错误处理
Inserts throw a 插入引发BulkWriteError
exception.BulkWriteError
异常。
Excluding write concern errors, ordered operations stop after an error, while unordered operations continue to process any remaining write operations in the queue.除了写入关注错误,有序操作在错误后停止,而无序操作继续处理队列中的任何剩余写入操作。
Write concern errors are displayed in the 写入关注错误显示在writeConcernErrors
field, while all other errors are displayed in the writeErrors
field. writeConcernErrors
字段中,而所有其他错误都显示在writeErrors
字段。If an error is encountered, the number of successful write operations are displayed instead of a list of inserted _ids. 如果遇到错误,将显示成功写入操作的次数,而不是插入的_id
列表。Ordered operations display the single error encountered while unordered operations display each error in an array.有序操作显示遇到的单个错误,而无序操作显示数组中的每个错误。
Transactions事务
db.collection.insertMany()
can be used inside multi-document transactions.可以在多文档事务中使用。
In most cases, multi-document transaction incurs a greater performance cost over single document writes, and the availability of multi-document transactions should not be a replacement for effective schema design. 在大多数情况下,与单文档写入相比,多文档事务会产生更高的性能成本,并且多文档事务的可用性不应取代有效的模式设计。For many scenarios, the denormalized data model (embedded documents and arrays) will continue to be optimal for your data and use cases. 对于许多场景,非规范化数据模型(嵌入文档和数组)将继续是您的数据和用例的最佳选择。That is, for many scenarios, modeling your data appropriately will minimize the need for multi-document transactions.也就是说,对于许多场景,对数据进行适当建模将最大限度地减少对多文档事务的需求。
For additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations.有关其他事务使用注意事项(如运行时限制和操作日志大小限制),请参阅生产注意事项。
Collection Creation in Transactions事务记录中的集合创建
Starting in MongoDB 4.4, you can create collections and indexes inside a multi-document transaction if the transaction is not a cross-shard write transaction.从MongoDB 4.4开始,如果多文档事务不是跨分片写入事务,则可以在该事务内创建集合和索引。
Specifically, in MongoDB 4.4 and greater, if you specify an insert on a non-existing collection in a transaction, the collection is implicitly created.具体来说,在MongoDB 4.4及更高版本中,如果在事务中的不存在集合上指定插入,则会隐式创建该集合。
In MongoDB 4.4 and earlier, the operation must be run on an existing collection.在MongoDB 4.4及更早版本中,操作必须在现有集合上运行。
See also: 另请参阅:
Write Concerns and Transactions撰写关注事项和事务
Do not explicitly set the write concern for the operation if run in a transaction. 如果在事务中运行,请不要显式设置操作的写入关注。To use write concern with transactions, see Transactions and Write Concern.要在事务中使用写入关注,请参阅事务和写入关注。
Examples实例
The following examples insert documents into the 以下示例将文档插入到products
collection.products
集合中。
Insert Several Document without Specifying an _id
Field插入多个文档而不指定_id
字段
_id
FieldThe following example uses 以下示例使用db.collection.insertMany()
to insert documents that do not contain the _id
field:db.collection.insertMany()
插入不包含_id
字段的文档:
try {
db.products.insertMany( [
{ item: "card", qty: 15 },
{ item: "envelope", qty: 20 },
{ item: "stamps" , qty: 30 }
] );
} catch (e) {
print (e);
}
The operation returns the following document:该操作返回以下文档:
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("562a94d381cb9f1cd6eb0e1a"),
ObjectId("562a94d381cb9f1cd6eb0e1b"),
ObjectId("562a94d381cb9f1cd6eb0e1c")
]
}
Because the documents did not include 由于文档不包括_id
, mongod
creates and adds the _id
field for each document and assigns it a unique ObjectId()
value._id
,mongod
为每个文档创建并添加_id
字段,并为其分配一个唯一的ObjectId()
值。
The ObjectId
values are specific to the machine and time when the operation is run. As such, your values may differ from those in the example.ObjectId
值特定于运行操作时的机器和时间。因此,您的值可能与示例中的值不同。
Insert Several Document Specifying an _id
Field插入指定_id
字段的多个文档
_id
FieldThe following example/operation uses 以下示例/操作使用insertMany()
to insert documents that include the _id
field. The value of _id
must be unique within the collection to avoid a duplicate key error.insertMany()
插入包含_id
字段的文档。_id
的值在集合中必须是唯一的,以避免出现重复的键错误。
try {
db.products.insertMany( [
{ _id: 10, item: "large box", qty: 20 },
{ _id: 11, item: "small box", qty: 55 },
{ _id: 12, item: "medium box", qty: 30 }
] );
} catch (e) {
print (e);
}
The operation returns the following document:该操作返回以下文档:
{ "acknowledged" : true, "insertedIds" : [ 10, 11, 12 ] }
Inserting a duplicate value for any key that is part of a unique index, such as 为作为唯一索引一部分的任何键(如_id
, throws an exception. The following attempts to insert a document with a _id
value that already exists:_id
)插入重复值会引发异常。以下尝试插入已存在_id
值的文档:
try {
db.products.insertMany( [
{ _id: 13, item: "envelopes", qty: 60 },
{ _id: 13, item: "stamps", qty: 110 },
{ _id: 14, item: "packing tape", qty: 38 }
] );
} catch (e) {
print (e);
}
Since 由于_id: 13
already exists, the following exception is thrown:_id:13
已经存在,因此引发以下异常:
BulkWriteError({
"writeErrors" : [
{
"index" : 0,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: inventory.products index: _id_ dup key: { : 13.0 }",
"op" : {
"_id" : 13,
"item" : "stamps",
"qty" : 110
}
}
],
"writeConcernErrors" : [ ],
"nInserted" : 1,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
Note that one document was inserted: The first document of 请注意,插入了一个文档:_id: 13
will insert successfully, but the second insert will fail. This will also stop additional documents left in the queue from being inserted._id:13
的第一个文档将成功插入,但第二个插入将失败。这也将阻止插入队列中剩余的其他文档。
With 在ordered
to false
, the insert operation would continue with any remaining documents.ordered
为false
的情况下,插入操作将继续处理任何剩余的文档。
Unordered Inserts无序插入
The following attempts to insert multiple documents with 以下尝试插入多个_id
field and ordered: false
. The array of documents contains two documents with duplicate _id
fields._id
字段为且ordered: false
的文档。文档数组包含两个具有重复_id
字段的文档。
try {
db.products.insertMany( [
{ _id: 10, item: "large box", qty: 20 },
{ _id: 11, item: "small box", qty: 55 },
{ _id: 11, item: "medium box", qty: 30 },
{ _id: 12, item: "envelope", qty: 100},
{ _id: 13, item: "stamps", qty: 125 },
{ _id: 13, item: "tape", qty: 20},
{ _id: 14, item: "bubble wrap", qty: 30}
], { ordered: false } );
} catch (e) {
print (e);
}
The operation throws the following exception:该操作引发以下异常:
BulkWriteError({
"writeErrors" : [
{
"index" : 2,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: inventory.products index: _id_ dup key: { : 11.0 }",
"op" : {
"_id" : 11,
"item" : "medium box",
"qty" : 30
}
},
{
"index" : 5,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: inventory.products index: _id_ dup key: { : 13.0 }",
"op" : {
"_id" : 13,
"item" : "tape",
"qty" : 20
}
}
],
"writeConcernErrors" : [ ],
"nInserted" : 5,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
While the document with 当item: "medium box"
and item: "tape"
failed to insert due to duplicate _id
values, nInserted
shows that the remaining 5 documents were inserted.item: "medium box"
和item: "tape"
的文档由于_id
值重复而无法插入时,nInserted
显示已插入其余5个文档。
Using Write Concern使用写入关注
Given a three member replica set, the following operation specifies a 给定一个由三个成员组成的复制集,以下操作指定w
of majority
and wtimeout
of 100
:w
为多数,wtimeout
为100
:
try {
db.products.insertMany(
[
{ _id: 10, item: "large box", qty: 20 },
{ _id: 11, item: "small box", qty: 55 },
{ _id: 12, item: "medium box", qty: 30 }
],
{ w: "majority", wtimeout: 100 }
);
} catch (e) {
print (e);
}
If the primary and at least one secondary acknowledge each write operation within 100 milliseconds, it returns:如果主和至少一个辅助在100毫秒内确认每个写入操作,则返回:
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("562a94d381cb9f1cd6eb0e1a"),
ObjectId("562a94d381cb9f1cd6eb0e1b"),
ObjectId("562a94d381cb9f1cd6eb0e1c")
]
}
If the total time required for all required nodes in the replica set to acknowledge the write operation is greater than 如果副本集中所有所需节点确认写入操作所需的总时间大于wtimeout
, the following writeConcernError
is displayed when the wtimeout
period has passed.wtimeout
,则在wtimeout
时间段过后,将显示以下writeConcernError
。
This operation returns:此操作返回:
WriteConcernError({
"code" : 64,
"errmsg" : "waiting for replication timed out",
"errInfo" : {
"wtimeout" : true,
"writeConcern" : { // Added in MongoDB 4.4
"w" : "majority",
"wtimeout" : 100,
"provenance" : "getLastErrorDefaults"
}
}
})