Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs Menu
Docs Home
/ /

db.collection.insert() (mongosh method)

Important

Deprecated mongosh Method

This method is deprecated in mongosh. For alternative methods, see Compatibility Changes with Legacy mongo Shell.

db.collection.insert()

Inserts a document or documents into a collection.

Returns:
  • A WriteResult object for single inserts.

  • A BulkWriteResult object for bulk inserts.

db.collection.insert() has the following syntax:

db.collection.insert(
<document or array of documents>,
{
writeConcern: <document>,
ordered: <boolean>
}
)
Parameter
Type
Description

document

document or array

A document or array of documents to insert into the collection.

writeConcern

document

Optional. A document expressing the write concern. Omit to use the default write concern. See 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. If true, perform an ordered insert of the documents in the array, and if an error occurs with one of documents, MongoDB will return without processing the remaining documents in the array.

If false, perform an unordered insert, and if an error occurs with one of documents, continue processing the remaining documents in the array.

Defaults to true.

The insert() method uses the insert command, which uses the default write concern. To specify a different write concern, include the write concern in the options parameter.

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

If the document to insert does not specify an _id field, then mongod adds the _id field and assigns 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.

insert() can be used inside distributed 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) 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.

You can create collections and indexes inside a distributed transaction 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.

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.

If an insert() operation successfully inserts a document, the operation adds an entry on the oplog (operations log). If the operation fails, the operation does not add an entry on the oplog.

The examples on this page use data from the sample_mflix sample dataset. For details on how to load this dataset into your self-managed MongoDB deployment, see Load the sample dataset. 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.

The following example inserts a document without an _id field into the movies collection:

db.movies.insert( { title: "Inception", year: 2010, genres: [ "Action", "Sci-Fi" ] } )
{
acknowledged: true,
insertedIds: { '0': "..." }
}

Because the inserted document does not include _id, mongod creates and adds the _id field 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.

The following example specifies the _id field in the document inserted into the movies collection. The value of _id must be unique within the collection to avoid a duplicate key error.

db.movies.insert( { _id: 10, title: "Inception", year: 2010 } )
{
acknowledged: true,
insertedIds: { '0': 10 }
}

The following example performs a bulk insert by passing an array of documents to insert(). By default, MongoDB performs an ordered insert. With ordered inserts, if an error occurs during an insert of one of the documents, MongoDB returns on error without processing the remaining documents in the array.

The first document specifies an _id field. Because the second and third documents do not contain an _id field, mongod creates and adds the _id field for those documents during the insert:

db.movies.insert(
[
{ _id: 11, title: "Inception", year: 2010, genres: [ "Action", "Sci-Fi" ] },
{ title: "The Matrix", year: 1999 },
{ title: "Interstellar", year: 2014 }
]
)
{
acknowledged: true,
insertedIds: {
'0': 11,
'1': "...",
'2': "..."
}
}

The following example performs an unordered insert of three documents. With unordered inserts, if an error occurs during an insert of one of the documents, MongoDB continues to insert the remaining documents in the array.

db.movies.insert(
[
{ _id: 20, title: "2001: A Space Odyssey", year: 1968 },
{ _id: 21, title: "A Clockwork Orange", year: 1971 },
{ _id: 22, title: "The Shining", year: 1980 }
],
{ ordered: false }
)

The following operation to a replica set specifies a write concern of w: 2 with a wtimeout of 5000 milliseconds. This operation either returns after the write propagates to both the primary and one secondary, or times out after 5 seconds.

db.movies.insert(
{ title: "The Revenant", year: 2015 },
{ writeConcern: { w: 2, j: true, wtimeout: 5000 } }
)

When passed a single document, insert() returns a WriteResult() object.

Upon success, the returned WriteResult object contains information on the number of documents inserted:

WriteResult({ "nInserted" : 1 })

If insert() encounters write concern errors, the results include the WriteResult.writeConcernError field:

WriteResult({
"nInserted" : 1,
"writeConcernError"({
"code" : 64,
"errmsg" : "waiting for replication timed out",
"errInfo" : {
"wtimeout" : true,
"writeConcern" : {
"w" : "majority",
"wtimeout" : 100,
"provenance" : "getLastErrorDefaults"
}
}
})

If insert() encounters a non-write concern error, the results include the WriteResult.writeError field:

WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.foo.$_id_ dup key: { : 1.0 }"
}
})

When passed an array of documents, insert() returns a BulkWriteResult() object.

Back

db.collection.hideIndex

On this page