db.collection.insertMany()

Definition

  • db.collection.insertMany()

mongo Shell Method

This page documents the mongo shell method, and doesnot refer to the MongoDB Node.js driver (or any other driver)method. For corresponding MongoDB driver API, refer to your specificMongoDB driver documentation instead.

New in version 3.2.

Inserts multiple documents into a collection.

The insertMany() method has the followingsyntax:

  1. db.collection.insertMany(
  2. [ <document 1> , <document 2>, ... ],
  3. {
  4. writeConcern: <document>,
  5. ordered: <boolean>
  6. }
  7. )

ParameterTypeDescriptiondocumentdocumentAn array of documents to insert into the collection.writeConcerndocumentOptional. 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 ina transaction. To use write concern with transactions, seeTransactions and Write Concern.orderedbooleanOptional. A boolean specifying whether the mongod instance should performan ordered or unordered insert. Defaults to true.

Returns:A document containing:

  • A boolean acknowledged as true if the operation ran withwrite concern or false if write concern was disabled
  • An array of _id for each successfully inserted documents

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 unorderedformat and may be reordered by mongod to increase performance.Applications should not depend on ordering of inserts if using an unorderedinsertMany().

The number of operations in each group cannot exceed the value ofthe maxWriteBatchSize ofthe 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 groupexceeds this limit,the client driver divides the group into smaller groups with countsless than or equal to the value of the limit. For example, with themaxWriteBatchSize value of 100,000, if the queue consists of200,000 operations, the driver creates 2 groups, each with100,000 operations.

Note

The driver only divides the group into smaller groups when usingthe high-level API. If usingdb.runCommand() directly(for example, when writing a driver), MongoDB throws an error whenattempting to execute a write batch which exceeds the limit.

Starting in MongoDB 3.6, once the error report for a single batch growstoo large, MongoDB truncates all remaining error messages to the emptystring. Currently, begins once there are at least 2 error messages withtotal size greater than 1MB.

The sizes and grouping mechanics are internal performance details andare subject to change in future versions.

Executing an ordered list of operations on asharded collection will generally be slower than executing anunordered listsince with an ordered list, each operation must wait for the previousoperation 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 mongodadds the _id field and assign a uniqueObjectId for the document. Mostdrivers create an ObjectId and insert the _id field, but themongod will create and populate the _id if the driver orapplication does not.

If the document contains an _id field, the _id value must beunique within the collection to avoid duplicate key error.

Explainability

insertMany() is not compatible withdb.collection.explain().

Use insert() instead.

Error Handling

Inserts throw a BulkWriteError exception.

Excluding Write Concern errors, ordered operations stopafter an error, while unordered operations continue to process anyremaining write operations in the queue.

Write concern errors are displayed in the writeConcernErrors field, whileall other errors are displayed in the writeErrors field. If an error isencountered, the number of successful write operations are displayed insteadof a list of inserted _ids. Ordered operations display the single errorencountered while unordered operations display each error in an array.

Transactions

db.collection.insertMany() can be used inside multi-document transactions.

The collection must already exist. An insert operation thatwould result in the creation of a new collection are not allowed in atransaction.

Do not explicitly set the write concern for the operation if run ina transaction. To use write concern with transactions, seeTransactions and Write Concern.

Important

In most cases, multi-document transaction incurs a greaterperformance cost over single document writes, and theavailability of multi-document transactions should not be areplacement for effective schema design. For many scenarios, thedenormalized data model (embedded documents and arrays) will continue to be optimal for yourdata and use cases. That is, for many scenarios, modeling your dataappropriately will minimize the need for multi-documenttransactions.

For additional transactions usage considerations(such as runtime limit and oplog size limit), see alsoProduction Considerations.

Examples

The following examples insert documents into the productscollection.

Insert Several Document without Specifying an _id Field

The following example uses db.collection.insertMany() to insertdocuments that do not contain the _id field:

  1. try {
  2. db.products.insertMany( [
  3. { item: "card", qty: 15 },
  4. { item: "envelope", qty: 20 },
  5. { item: "stamps" , qty: 30 }
  6. ] );
  7. } catch (e) {
  8. print (e);
  9. }

The operation returns the following document:

  1. {
  2. "acknowledged" : true,
  3. "insertedIds" : [
  4. ObjectId("562a94d381cb9f1cd6eb0e1a"),
  5. ObjectId("562a94d381cb9f1cd6eb0e1b"),
  6. ObjectId("562a94d381cb9f1cd6eb0e1c")
  7. ]
  8. }

Because the documents did not include _id,mongod creates and adds the _id field for each document andassigns it a unique ObjectId value.

The ObjectId values are specific to the machine and time when theoperation is run. As such, your values may differ from those in theexample.

Insert Several Document Specifying an _id Field

The following example/operation uses insertMany() toinsert documents that include the _id field. The value of _id must beunique within the collection to avoid a duplicate key error.

  1. try {
  2. db.products.insertMany( [
  3. { _id: 10, item: "large box", qty: 20 },
  4. { _id: 11, item: "small box", qty: 55 },
  5. { _id: 12, item: "medium box", qty: 30 }
  6. ] );
  7. } catch (e) {
  8. print (e);
  9. }

The operation returns the following document:

  1. { "acknowledged" : true, "insertedIds" : [ 10, 11, 12 ] }

Inserting a duplicate value for any key that is part of a uniqueindex, such as _id, throws an exception. The following attempts to inserta document with a _id value that already exists:

  1. try {
  2. db.products.insertMany( [
  3. { _id: 13, item: "envelopes", qty: 60 },
  4. { _id: 13, item: "stamps", qty: 110 },
  5. { _id: 14, item: "packing tape", qty: 38 }
  6. ] );
  7. } catch (e) {
  8. print (e);
  9. }

Since _id: 13 already exists, the following exception is thrown:

  1. BulkWriteError({
  2. "writeErrors" : [
  3. {
  4. "index" : 0,
  5. "code" : 11000,
  6. "errmsg" : "E11000 duplicate key error collection: inventory.products index: _id_ dup key: { : 13.0 }",
  7. "op" : {
  8. "_id" : 13,
  9. "item" : "stamps",
  10. "qty" : 110
  11. }
  12. }
  13. ],
  14. "writeConcernErrors" : [ ],
  15. "nInserted" : 1,
  16. "nUpserted" : 0,
  17. "nMatched" : 0,
  18. "nModified" : 0,
  19. "nRemoved" : 0,
  20. "upserted" : [ ]
  21. })

Note that one document was inserted: The first document of _id: 13 willinsert successfully, but the second insert will fail. This will also stopadditional documents left in the queue from being inserted.

With ordered to false, the insert operation would continue with anyremaining documents.

Unordered Inserts

The following attempts to insert multiple documents with _id field andordered: false. The array of documents contains two documents withduplicate _id fields.

  1. try {
  2. db.products.insertMany( [
  3. { _id: 10, item: "large box", qty: 20 },
  4. { _id: 11, item: "small box", qty: 55 },
  5. { _id: 11, item: "medium box", qty: 30 },
  6. { _id: 12, item: "envelope", qty: 100},
  7. { _id: 13, item: "stamps", qty: 125 },
  8. { _id: 13, item: "tape", qty: 20},
  9. { _id: 14, item: "bubble wrap", qty: 30}
  10. ], { ordered: false } );
  11. } catch (e) {
  12. print (e);
  13. }

The operation throws the following exception:

  1. BulkWriteError({
  2. "writeErrors" : [
  3. {
  4. "index" : 2,
  5. "code" : 11000,
  6. "errmsg" : "E11000 duplicate key error collection: inventory.products index: _id_ dup key: { : 11.0 }",
  7. "op" : {
  8. "_id" : 11,
  9. "item" : "medium box",
  10. "qty" : 30
  11. }
  12. },
  13. {
  14. "index" : 5,
  15. "code" : 11000,
  16. "errmsg" : "E11000 duplicate key error collection: inventory.products index: _id_ dup key: { : 13.0 }",
  17. "op" : {
  18. "_id" : 13,
  19. "item" : "tape",
  20. "qty" : 20
  21. }
  22. }
  23. ],
  24. "writeConcernErrors" : [ ],
  25. "nInserted" : 5,
  26. "nUpserted" : 0,
  27. "nMatched" : 0,
  28. "nModified" : 0,
  29. "nRemoved" : 0,
  30. "upserted" : [ ]
  31. })

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 aw of majority and wtimeout of 100:

  1. try {
  2. db.products.insertMany(
  3. [
  4. { _id: 10, item: "large box", qty: 20 },
  5. { _id: 11, item: "small box", qty: 55 },
  6. { _id: 12, item: "medium box", qty: 30 }
  7. ],
  8. { w: "majority", wtimeout: 100 }
  9. );
  10. } catch (e) {
  11. print (e);
  12. }

If the primary and at least one secondary acknowledge each write operationwithin 100 milliseconds, it returns:

  1. {
  2. "acknowledged" : true,
  3. "insertedIds" : [
  4. ObjectId("562a94d381cb9f1cd6eb0e1a"),
  5. ObjectId("562a94d381cb9f1cd6eb0e1b"),
  6. ObjectId("562a94d381cb9f1cd6eb0e1c")
  7. ]
  8. }

If the total time required for all required nodes in the replica set toacknowledge the write operation is greater than wtimeout,the following writeConcernError is displayed when the wtimeout periodhas passed.

This operation returns:

  1. WriteConcernError({
  2. "code" : 64,
  3. "errInfo" : {
  4. "wtimeout" : true
  5. },
  6. "errmsg" : "waiting for replication timed out"
  7. })