On this page本页内容
db.collection.
insertMany
()¶mongo
Shell Method
This page documents the 本页记录了mongo
shell method, and does not refer to the MongoDB Node.js driver (or any other driver) method. mongo
shell方法,未提及MongoDB Node.js驱动程序(或任何其他驱动程序)方法。For corresponding MongoDB driver API, refer to your specific MongoDB driver documentation instead.有关相应的MongoDB驱动程序API,请参阅特定的MongoDB驱动程序文档。
New in version 3.2.版本3.2中的新功能。
Inserts multiple documents into a collection.将多个文档插入到集合中。
The insertMany()
method has the following syntax:语法如下所示:
document |
document | |
writeConcern |
document |
|
ordered |
boolean | mongod instance should perform an ordered or unordered insert. mongod 实例应该执行有序插入还是无序插入。true .true 。 |
|
Given an array of documents, 给定一个文档数组,insertMany()
inserts each document in the array into the collection.insertMany()
将数组中的每个文档插入集合。
By default documents are inserted in order.默认情况下,文档按顺序插入。
If 如果ordered
is set to false, documents are inserted in an unordered format and may be reordered by mongod
to increase performance. ordered
设置为false
,文档将以无序格式插入,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
值。As of MongoDB 3.6, this value is 截至MongoDB 3.6,该值为100,000
. 100000
。This value is shown in the 此值显示在isMaster.maxWriteBatchSize
field.isMaster.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. limit
,客户端驱动程序会将该组划分为计数小于或等于该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
个操作。
Note
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在尝试执行超出限制的写入批处理时会抛出错误。
Starting in MongoDB 3.6, once the error report for a single batch grows too large, MongoDB truncates all remaining error messages to the empty string. 从MongoDB 3.6开始,一旦单个批次的错误报告变得太大,MongoDB就会将所有剩余的错误消息截断为空字符串。Currently, begins once there are at least 2 error messages with total size greater than 目前,当至少有2条总大小大于1MB
.1MB
的错误消息时开始。
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.
If the collection does not exist, then 如果集合不存在,则insertMany()
creates the collection on successful write.insertMany()
会在成功写入时创建集合。
_id
If the document does not specify an _id field, then mongod
adds the _id
field and assign a unique ObjectId
for the document. 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.
If the document contains an 如果文档包含_id
field, the _id
value must be unique within the collection to avoid duplicate key error._id
字段,_id
值在集合中必须是唯一的,以避免重复键错误。
insertMany()
is not compatible with db.collection.explain()
.
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. If an error is encountered, the number of successful write operations are displayed instead of a list of inserted _ids. Ordered operations display the single error encountered while unordered operations display each error in an array.有序操作显示遇到的单个错误,而无序操作显示数组中的每个错误。
db.collection.insertMany()
can be used inside multi-document transactions.可以在多文档事务中使用。
Important
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.有关其他事务使用注意事项(如运行时限制和oplog大小限制),请参阅生产注意事项。
Starting in MongoDB 4.4 with feature compatibility version (fcv) "4.4"
, you can create collections and indexes inside a multi-document transaction if the transaction is not a cross-shard write transaction.
As such, for feature compatibility version (fcv) "4.4"
and greater, if you specify an insert on a non-existing collection in a transaction, the collection is implicitly created.
If the feature compatibility version (fcv) is 如果功能兼容版本(fcv)为"4.2"
or less, the operation must be against an existing collection."4.2"
或更低,则操作必须针对现有集合。
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.要将写关注点用于事务,请参阅事务和写关注点。
The following examples insert documents into the 以下示例将文档插入到products
collection.products
集合中。
_id
Field_id
字段的情况下插入多个文档¶The following example uses 以下示例使用db.collection.insertMany()
to insert documents that do not contain the _id
field:db.collection.insertMany()
插入不包含_id
字段的文档:
The operation returns the following document:该操作将返回以下文档:
Because the documents did not include _id
, mongod
creates and adds the _id
field for each document and assigns it a unique ObjectId
value.
The ObjectId
values are specific to the machine and time when the operation is run. ObjectId
值特定于机器和运行操作的时间。As such, your values may differ from those in the example.例如,你的价值观可能与你的例子中的不同。
_id
Field_id
字段的文档¶The 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._id
的值在集合中必须是唯一的,以避免重复的密钥错误。
The operation returns the following document:该操作将返回以下文档:
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:
Since 由于_id: 13
already exists, the following exception is thrown:_id:13
已经存在,将引发以下异常:
Note that one document was inserted: The first document of 请注意,插入了一个文档:_id: 13
will insert successfully, but the second insert will fail. _id: 13
的第一个文档将成功插入,但第二个插入将失败。This will also stop additional documents left in the queue from being inserted.这也将阻止插入队列中剩余的其他文档。
With 如果ordered
to false
, the insert operation would continue with any remaining documents.ordered
为false
,则插入操作将继续处理所有剩余的文档。
The following attempts to insert multiple documents with _id
field and ordered: false
. The array of documents contains two documents with duplicate _id
fields.
The operation throws the following exception:该操作引发以下异常:
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.
Given a three member replica set, the following operation specifies a 给定一个由三个成员组成的副本集,以下操作指定w
of majority
and wtimeout
of 100
:w
为majority
,wtimeout
为100
:
If the primary and at least one secondary acknowledge each write operation within 100 milliseconds, it returns:如果主设备和至少一个辅助设备在100毫秒内确认每个写入操作,则返回:
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:此操作返回:
See also参阅