db.collection.insertOne()

Definition

  • db.collection.insertOne()

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 a document into a collection.

The insertOne() method has the followingsyntax:

  1. db.collection.insertOne(
  2. <document>,
  3. {
  4. writeConcern: <document>
  5. }
  6. )

ParameterTypeDescriptiondocumentdocumentA document 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.

Returns:A document containing:

  • A boolean acknowledged as true if the operation ran withwrite concern or false if write concern was disabled.
  • A field insertedId with the _id value of theinserted document.

Behaviors

Collection Creation

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

_id Field

If the document does not specify an _id field, then mongodwill 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.

Explainability

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

Use insert() instead.

Error Handling

On error, db.collection.insertOne() throws either a writeErroror writeConcernError exception.

Transactions

db.collection.insertOne() 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

Insert a Document without Specifying an _id Field

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

  1. try {
  2. db.products.insertOne( { item: "card", qty: 15 } );
  3. } catch (e) {
  4. print (e);
  5. };

The operation returns the following document:

  1. {
  2. "acknowledged" : true,
  3. "insertedId" : ObjectId("56fc40f9d735c28df206d078")
  4. }

Because the documents did not include _id,mongod creates and adds the _id field 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 a Document Specifying an _id Field

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

  1. try {
  2. db.products.insertOne( { _id: 10, item: "box", qty: 20 } );
  3. } catch (e) {
  4. print (e);
  5. }

The operation returns the following:

  1. { "acknowledged" : true, "insertedId" : 10 }

Inserting an 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.insertOne( { _id: 10, "item" : "packing peanuts", "qty" : 200 } );
  3. } catch (e) {
  4. print (e);
  5. }

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

  1. WriteError({
  2. "index" : 0,
  3. "code" : 11000,
  4. "errmsg" : "E11000 duplicate key error collection: inventory.products index: _id_ dup key: { : 10.0 }",
  5. "op" : {
  6. "_id" : 10,
  7. "item" : "packing peanuts",
  8. "qty" : 200
  9. }
  10. })

Increase Write Concern

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

  1. try {
  2. db.products.insertOne(
  3. { "item": "envelopes", "qty": 100, type: "Self-Sealing" },
  4. { writeConcern: { w : "majority", wtimeout : 100 } }
  5. );
  6. } catch (e) {
  7. print (e);
  8. }

If the acknowledgement takes longer than the wtimeout limit, the followingexception is thrown:

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

See also

To insert multiple documents, seedb.collection.insertMany()