> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

# db.collection.insertMany() (mongosh method)

## Definition

Inserts multiple documents into a collection.

A document containing:

- An `acknowledged` boolean, set to `true` if the operation ran with [write concern](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-write-concern) or `false` if write concern was disabled

- An `insertedIds` array, containing `_id` values for each successfully inserted document

## Compatibility

This method is available in deployments hosted in the following environments:

- [MongoDB Atlas](https://www.mongodb.com/docs/atlas): The fully managed service for MongoDB deployments in the cloud

**Note:**

This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see [Unsupported Commands.](https://www.mongodb.com/docs/atlas/unsupported-commands/)

- [MongoDB Enterprise](https://www.mongodb.com/docs/manual/administration/install-enterprise.md#std-label-install-mdb-enterprise): The subscription-based, self-managed version of MongoDB

- [MongoDB Community](https://www.mongodb.com/docs/manual/administration/install-community.md#std-label-install-mdb-community-edition): The source-available, free-to-use, and self-managed version of MongoDB

## Syntax

`db.collection.insertMany()` has the following syntax:

```javascript
db.collection.insertMany(
   [ <document 1> , <document 2>, ... ],
   {
      writeConcern: <document>,
      ordered: <boolean>
   }
)
```

### Parameters

| Parameter | Type | Description |
| --- | --- | --- |
| `document` | document | An array of documents to insert into the collection. |
| `writeConcern` | document | Optional. A document expressing the [write concern](https://www.mongodb.com/docs/manual/reference/write-concern.md#std-label-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.](https://www.mongodb.com/docs/manual/core/transactions.md#std-label-transactions-write-concern) |
| `ordered` | boolean | Optional. A boolean specifying whether the [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) instance should perform an ordered or unordered insert. Defaults to `true`. |

## Behaviors

Given an array of documents, `insertMany()` inserts each document in the array into the collection. There is no limit to the number of documents you can specify in the array.

### 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.

- If `ordered` is set to `false` and an insert fails, the server continues inserting records. Documents may be reordered by [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) to increase performance. Applications should not depend on ordering of inserts if using an unordered `insertMany()`.

Executing an [`ordered`](https://www.mongodb.com/docs/manual/reference/method/db.collection.initializeorderedbulkop.md#mongodb-method-db.collection.initializeOrderedBulkOp) list of operations on a sharded collection will generally be slower than executing an [`unordered`](https://www.mongodb.com/docs/manual/reference/method/db.collection.initializeunorderedbulkop.md#mongodb-method-db.collection.initializeUnorderedBulkOp) list since with an ordered list, each operation must wait for the previous operation to finish.

### Batching

The driver batches documents specified in the `insertMany()` array according to the [maxWriteBatchSize](https://www.mongodb.com/docs/manual/reference/limits.md#mongodb-limit-Write-Command-Batch-Limit-Size), which is 100,000 and cannot be modified. For example, if the `insertMany()` operation contains 250,000 documents, the driver creates three batches: two with 100,000 documents and one with 50,000 documents.

**Note:**

The driver only performs batching when using the high-level API. If you use [`db.runCommand()`](https://www.mongodb.com/docs/manual/reference/method/db.runcommand.md#mongodb-method-db.runCommand) directly (for example, when writing a driver), MongoDB throws an error when attempting to execute a write batch that exceeds the `maxWriteBatchSize` limit.

If the error report for a single batch grows too large, MongoDB truncates all remaining error messages. If there are at least two error messages with size greater than `1MB`, those messages are truncated.

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

### Collection and `_id` Field Creation

If the collection does not exist, then `insertMany()` creates the collection.

If the document to insert does not specify an [\_id](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-_id) field, then [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) adds the `_id` field and assigns a unique [`ObjectId()`](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-ObjectId) for the document. Most drivers create an ObjectId and insert the `_id` field, but the [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.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.

### Explainability

`insertMany()` is not compatible with [`db.collection.explain()`.](https://www.mongodb.com/docs/manual/reference/method/db.collection.explain.md#mongodb-method-db.collection.explain)

### Error Handling

Inserts throw a `BulkWriteError` exception.

Excluding [write concern](https://www.mongodb.com/docs/manual/reference/write-concern.md#std-label-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.

#### Schema Validation Errors

If your collection uses [schema validation](https://www.mongodb.com/docs/manual/core/schema-validation.md#std-label-schema-validation-overview) and has `validationAction` set to `error`, inserting an invalid document with `insertMany()` throws a `writeError`. Documents that precede the invalid document in the `documents` array are written to the collection. The value of the `ordered` field determines if the remaining valid documents are inserted.

### Transactions

`insertMany()` can be used inside [distributed transactions.](https://www.mongodb.com/docs/manual/core/transactions.md#std-label-transactions)

**Important:**

In most cases, a distributed transaction incurs a greater performance cost over single document writes, and the availability of distributed transactions should not be a replacement for effective schema design. For many scenarios, the [denormalized data model (embedded documents and arrays)](https://www.mongodb.com/docs/manual/data-modeling/embedding.md#std-label-data-modeling-embedding) 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 distributed transactions.

For additional transactions usage considerations (such as runtime limit and oplog size limit), see also [Production Considerations.](https://www.mongodb.com/docs/manual/core/transactions-production-consideration.md#std-label-production-considerations)

#### Collection Creation in Transactions

You can create collections and indexes inside a [distributed transaction](https://www.mongodb.com/docs/manual/core/transactions.md#std-label-transactions-create-collections-indexes) if the transaction is not a cross-shard write transaction.

If you specify an insert on a non-existing collection in a transaction, MongoDB creates the collection implicitly.

#### 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.](https://www.mongodb.com/docs/manual/core/transactions.md#std-label-transactions-write-concern)

### Performance Consideration for Random Data

If an operation inserts a large amount of random data (for example, hashed indexes) on an indexed field, insert performance may decrease. Bulk inserts of random data create random index entries, which increase the size of the index. If the index reaches the size that requires each random insert to access a different index entry, the inserts result in a high rate of WiredTiger cache eviction and replacement. When this happens, the index is no longer fully in cache and is updated on disk, which decreases performance.

To improve the performance of bulk inserts of random data on indexed fields, you can either:

- Drop the index, then recreate it after you insert the random data.

- Insert the data into an empty unindexed collection.

Creating the index after the bulk insert sorts the data in memory and performs an ordered insert on all indexes.

### Oplog Entries

MongoDB consolidates operations that insert multiple documents, such as `insertMany()` or multiple `insertOne()` commands within a [`db.collection.bulkWrite()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkwrite.md#mongodb-method-db.collection.bulkWrite) operation, into a single entry in the [oplog](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-oplog). If the operation fails, the operation does not add an entry on the oplog.

## Examples

The examples on this page use data from the [sample\_mflix dataset](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix). For details on how to load this dataset into your self-managed MongoDB deployment, see [Load the Sample Dataset](https://www.mongodb.com/docs/manual/sample-data/load-sample-data-local.md#std-label-sample-dataset-local). If you made any modifications to the sample databases, you may need to drop and recreate the databases to run the examples on this page.

### Insert Several Documents without Specifying an `_id` Field

The following example inserts three documents without `_id` fields into the `movies` collection:

```javascript
db.movies.insertMany( [
   { title: "Inception", year: 2010, genres: [ "Action", "Sci-Fi" ] },
   { title: "The Matrix", year: 1999, genres: [ "Action", "Sci-Fi" ] },
   { title: "Interstellar", year: 2014, genres: [ "Adventure", "Sci-Fi" ] }
] )

```

**Output:**

```javascript
{
  acknowledged: true,
  insertedIds: {
    '0': "...",
    '1': "...",
    '2': "..."
  }
}

```

Because the documents do not include `_id`, [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) creates and adds the `_id` field for each document and assigns it a unique [`ObjectId()`](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-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 inserts documents that specify the `_id` field into the `movies` collection. The value of `_id` must be unique within the collection to avoid a duplicate key error:

```javascript
db.movies.insertMany( [
   { _id: 10, title: "Inception", year: 2010 },
   { _id: 11, title: "The Matrix", year: 1999 },
   { _id: 12, title: "Interstellar", year: 2014 }
] )

```

**Output:**

```javascript
{
  acknowledged: true,
  insertedIds: { '0': 10, '1': 11, '2': 12 }
}

```

Inserting a duplicate value for any key that is part of a [unique index](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-unique-index), such as `_id`, throws an exception. The following attempts to insert a document with a `_id` value that already exists:

```javascript
try {
   db.movies.insertMany( [
      { _id: 13, title: "Inception", year: 2010 },
      { _id: 13, title: "The Dark Knight", year: 2008 },
      { _id: 14, title: "Interstellar", year: 2014 }
   ] );
} catch (e) {
   print (e);
}
```

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

```javascript
BulkWriteError({
   "writeErrors" : [
      {
         "index" : 0,
         "code" : 11000,
         "errmsg" : "E11000 duplicate key error collection: sample_mflix.movies index: _id_ dup key: { : 13.0 }",
         "op" : {
            "_id" : 13,
            "title" : "The Dark Knight",
            "year" : 2008
         }
      }
   ],
   "writeConcernErrors" : [ ],
   "nInserted" : 1,
   "nUpserted" : 0,
   "nMatched" : 0,
   "nModified" : 0,
   "nRemoved" : 0,
   "upserted" : [ ]
})
```

Note that one document was inserted: the first document of `_id: 13` inserts successfully, but the second insert fails. The operation does not insert the remaining documents in the queue.

With `ordered` set to `false`, the insert operation continues 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.

```javascript
try {
   db.movies.insertMany( [
      { _id: 10, title: "Inception", year: 2010 },
      { _id: 11, title: "The Matrix", year: 1999 },
      { _id: 11, title: "Interstellar", year: 2014 },
      { _id: 12, title: "Arrival", year: 2016 },
      { _id: 13, title: "Blade Runner 2049", year: 2017 },
      { _id: 13, title: "Ex Machina", year: 2014 },
      { _id: 14, title: "Her", year: 2013 }
   ], { ordered: false } )
} catch (e) {
   print(e)
}

```

**Output:**

```javascript
MongoBulkWriteError: E11000 duplicate key error collection: sample_mflix.movies index: _id_ dup key: { _id: 11 }
Result: BulkWriteResult {
  insertedCount: 5,
  matchedCount: 0,
  modifiedCount: 0,
  deletedCount: 0,
  upsertedCount: 0,
  upsertedIds: {},
  insertedIds: {
    '0': 10,
    '1': 11,
    '3': 12,
    '4': 13,
    '6': 14
  }
}
Write Errors: [
  WriteError {
    err: {
      index: 2,
      code: 11000,
      errInfo: undefined,
      errmsg: 'E11000 duplicate key error collection: sample_mflix.movies index: _id_ dup key: { _id: 11 }'
    }
  },
  WriteError {
    err: {
      index: 5,
      code: 11000,
      errInfo: undefined,
      errmsg: 'E11000 duplicate key error collection: sample_mflix.movies index: _id_ dup key: { _id: 13 }'
    }
  }
]

```

Although the documents with `title: "Interstellar"` and `title: "Ex Machina"` fail to insert because of duplicate `_id` values, `insertedCount` shows that the remaining 5 documents insert successfully.

### Using Write Concern

Given a three member replica set, the following operation specifies a `w` of `majority` and `wtimeout` of `100`:

```javascript
try {
   db.movies.insertMany(
      [
         { _id: 15, title: "Forrest Gump", year: 1994 },
         { _id: 16, title: "Schindler's List", year: 1993 },
         { _id: 17, title: "Pulp Fiction", year: 1994 }
      ],
      { 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:

```javascript
{
  "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.

This operation returns:

```javascript
WriteConcernError({
   "code" : 64,
   "errmsg" : "waiting for replication timed out",
   "errInfo" : {
     "wtimeout" : true,
     "writeConcern" : {
       "w" : "majority",
       "wtimeout" : 100,
       "provenance" : "getLastErrorDefaults"
     }
   }
})
```
