Docs Menu
Docs Home
/
MongoDB Manual
/ / /

db.collection.insert()

On this page

  • Definition
  • Compatibility
  • Syntax
  • Behaviors
  • Examples
  • WriteResult
  • BulkWriteResult
db.collection.insert()

Important

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. For corresponding MongoDB driver API, refer to your specific MongoDB driver documentation instead.

Inserts a document or documents into a collection.

Returns:
  • A WriteResult object for single inserts.

  • A BulkWriteResult object for bulk inserts.

You can use db.collection.Insert() for deployments hosted in the following environments:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud

The insert() method 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() returns an object that contains the status of the operation.

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 the insert() method will create the collection.

If the document does not specify an _id field, then MongoDB will add the _id field and assign a unique ObjectId() for the document before inserting. 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.

db.collection.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.

Tip

See also:

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. If the collection does not exist, the insert() method creates the collection.

In the following example, the document passed to the insert() method does not contain the _id field:

db.products.insert( { item: "card", qty: 15 } )

During the insert, mongod will create the _id field and assign it a unique ObjectId() value, as verified by the inserted document:

{ "_id" : ObjectId("5063114bd386d8fadbd6b004"), "item" : "card", "qty" : 15 }

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.

In the following example, the document passed to the insert() method includes the _id field. The value of _id must be unique within the collection to avoid duplicate key error.

db.products.insert( { _id: 10, item: "box", qty: 20 } )

The operation inserts the following document in the products collection:

{ "_id" : 10, "item" : "box", "qty" : 20 }

The following example performs a bulk insert of three documents by passing an array of documents to the insert() method. 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 documents in the array do not need to have the same fields. For instance, the first document in the array has an _id field and a type field. Because the second and third documents do not contain an _id field, mongod will create the _id field for the second and third documents during the insert:

db.products.insert(
[
{ _id: 11, item: "pencil", qty: 50, type: "no.2" },
{ item: "pen", qty: 20 },
{ item: "eraser", qty: 25 }
]
)

The operation inserted the following three documents:

{ "_id" : 11, "item" : "pencil", "qty" : 50, "type" : "no.2" }
{ "_id" : ObjectId("51e0373c6f35bd826f47e9a0"), "item" : "pen", "qty" : 20 }
{ "_id" : ObjectId("51e0373c6f35bd826f47e9a1"), "item" : "eraser", "qty" : 25 }

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.products.insert(
[
{ _id: 20, item: "lamp", qty: 50, type: "desk" },
{ _id: 21, item: "lamp", qty: 20, type: "floor" },
{ _id: 22, item: "bulk", qty: 100 }
],
{ ordered: false }
)

The following operation to a replica set specifies a write concern of "w: majority" with a wtimeout of 5000 milliseconds such that the method returns after the write propagates to a majority of the voting replica set members or the method times out after 5 seconds.

db.products.insert(
{ item: "envelopes", qty : 100, type: "Clasp" },
{ writeConcern: { w: "majority", wtimeout: 5000 } }
)

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

The insert() returns a WriteResult() object that contains the status of the operation. Upon success, the WriteResult() object contains information on the number of documents inserted:

WriteResult({ "nInserted" : 1 })

If the insert() method 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" : { // Added in MongoDB 4.4
"w" : "majority",
"wtimeout" : 100,
"provenance" : "getLastErrorDefaults"
}
}
})

If the insert() method 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. See BulkWriteResult() for details.

Back

db.collection.hideIndex()