- Reference >
mongo
Shell Methods >- Collection Methods >
- db.collection.insertMany()
db.collection.insertMany()¶
On this page
Definition¶
-
db.collection.
insertMany
()¶ mongo
Shell MethodThis page documents the
mongo
shell method, and does not refer to the MongoDB Node.js driver (or any other driver) method. For corresponding MongoDB driver API, refer to your specific MongoDB driver documentation instead.New in version 3.2.
Inserts multiple documents into a collection.
The
insertMany()
method has the following syntax: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. Defaults totrue
.Returns: A document containing: - A boolean
acknowledged
astrue
if the operation ran with write concern orfalse
if write concern was disabled - An array of
_id
for each successfully inserted documents
- A boolean
Behaviors¶
Given an array of documents, insertMany()
inserts each document in the array into the collection.
Execution of Operations¶
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.
Applications should not depend on ordering of inserts if using an unordered
insertMany()
.
The number of operations in each group cannot exceed the value of
the maxWriteBatchSize
of
the database. As of MongoDB 3.6, this value is 100,000
.
This value is shown in the isMaster.maxWriteBatchSize
field.
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.
Note
The driver only divides the group into smaller groups when using the high-level 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.
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. Currently, begins once there are at least 2 error messages with
total size greater than 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.
Collection Creation¶
If the collection does not exist, then insertMany()
creates the collection on successful write.
_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. 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.
Error Handling¶
Inserts throw a BulkWriteError
exception.
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.
Transactions¶
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.
Collection Creation in Transactions¶
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
"4.2"
or less, the operation must be against an existing
collection.
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.
Insert Several Document without Specifying an _id
Field¶
The following example uses db.collection.insertMany()
to insert
documents that do not contain the _id
field:
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. As such, your values may differ from those in the
example.
Insert Several Document Specifying an _id
Field¶
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.
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:
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.
With ordered
to false
, the insert operation would continue with any
remaining documents.
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.
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.
Using Write Concern¶
Given a three member replica set, the following operation specifies a
w
of majority
and wtimeout
of 100
:
If the primary and at least one secondary acknowledge each write operation within 100 milliseconds, it returns:
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.
This operation returns:
See also