db.collection.insert()

Definition

  • db.collection.insert()

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.

Inserts a document or documents into a collection.

The insert() method has the followingsyntax:

Changed in version 2.6.

  1. db.collection.insert(
  2. <document or array of documents>,
  3. {
  4. writeConcern: <document>,
  5. ordered: <boolean>
  6. }
  7. )

ParameterTypeDescriptiondocumentdocument or arrayA document or array of documents to insert into the collection.writeConcerndocumentOptional. 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 ina transaction. To use write concern with transactions, seeTransactions and Write Concern.orderedbooleanOptional. If true, perform an ordered insert of the documents in thearray, and if an error occurs with one of documents, MongoDB willreturn without processing the remaining documents in the array.

If false, perform an unordered insert, and if an error occurswith one of documents, continue processing the remaining documentsin the array.

Defaults to true.

New in version 2.6.

Changed in version 2.6: The insert() returns an object thatcontains the status of the operation.

Returns:

Behaviors

Write Concern

Changed in version 2.6.

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

Create Collection

If the collection does not exist, then theinsert() method will create the collection.

_id Field

If the document does not specify an _id field, then MongoDBwill add the _id field and assign a uniqueObjectId for the document before inserting. 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.

Transactions

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

Insert a Document without Specifying an _id Field

In the following example, the document passed to theinsert() method does not contain the _idfield:

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

During the insert, mongod will create the _id field andassign it a unique ObjectId value, as verified bythe inserted document:

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

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 a Document Specifying an _id Field

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

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

The operation inserts the following document in the productscollection:

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

Insert Multiple Documents

The following example performs a bulk insert of three documents bypassing an array of documents to the insert()method. By default, MongoDB performs an ordered insert. Withordered inserts, if an error occurs during an insert of one of thedocuments, MongoDB returns on error without processing the remainingdocuments in the array.

The documents in the array do not need to have the same fields. Forinstance, the first document in the array has an _id field and atype field. Because the second and third documents do not containan _id field, mongod will create the _id field forthe second and third documents during the insert:

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

The operation inserted the following three documents:

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

Perform an Unordered Insert

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

  1. db.products.insert(
  2. [
  3. { _id: 20, item: "lamp", qty: 50, type: "desk" },
  4. { _id: 21, item: "lamp", qty: 20, type: "floor" },
  5. { _id: 22, item: "bulk", qty: 100 }
  6. ],
  7. { ordered: false }
  8. )

Override Default Write Concern

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

Changed in version 3.0: In previous versions, majority referred to the majority of allmembers of the replica set instead of the majority of the votingmembers.

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

WriteResult

Changed in version 2.6.

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

Successful Results

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

  1. WriteResult({ "nInserted" : 1 })

Write Concern Errors

If the insert() method encounters writeconcern errors, the results include theWriteResult.writeConcernError field:

  1. WriteResult({
  2. "nInserted" : 1,
  3. "writeConcernError" : {
  4. "code" : 64,
  5. "errmsg" : "waiting for replication timed out at shard-a"
  6. }
  7. })

Errors Unrelated to Write Concern

If the insert() method encounters a non-writeconcern error, the results include the WriteResult.writeErrorfield:

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

BulkWriteResult

Changed in version 2.6.

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