Navigation

db.collection.insertOne()

Definition

db.collection.insertOne()

New in version 3.2.

Inserts a document into a collection.

The insertOne() method has the following syntax:

db.collection.insertOne(
   <document>,
   {
      writeConcern: <document>
   }
)
Parameter Type Description
document document A document to insert into the collection.
writeConcern document

Optional. 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 in a transaction. To use write concern with transactions, see Transaction Options (Read Concern/Write Concern/Read Preference).

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

Behaviors

Collection Creation

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

_id Field

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

Explainability

insertOne() is not compatible with db.collection.explain().

Use insert() instead.

Error Handling

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

Transactions

db.collection.insertOne() supports multi-document transactions.

The collection must already exist. An insert operation that would result in the creation of a new collection are not allowed in a transaction.

Do not explicitly set the write concern for the operation if run in a transaction. To use write concern with transactions, see Transaction Options (Read Concern/Write Concern/Read Preference).

Important

In most cases, multi-document transaction incurs a greater performance cost over single document writes, and the availability of multi-document transaction 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 multi-document transactions.

Examples

Insert a Document without Specifying an _id Field

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

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

The operation returns the following document:

{
   "acknowledged" : true,
   "insertedId" : ObjectId("56fc40f9d735c28df206d078")
}

Because the documents did 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.

Insert a Document Specifying an _id Field

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

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

The operation returns the following:

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

Inserting an duplicate value for any key that is part of a unique index, such as _id, throws an exception. The following attempts to insert a document with a _id value that already exists:

try {
   db.products.insertOne( { _id: 10, "item" : "packing peanuts", "qty" : 200 } );
} catch (e) {
   print (e);
}

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

WriteError({
   "index" : 0,
   "code" : 11000,
   "errmsg" : "E11000 duplicate key error collection: inventory.products index: _id_ dup key: { : 10.0 }",
   "op" : {
      "_id" : 10,
      "item" : "packing peanuts",
      "qty" : 200
   }
})

Increase Write Concern

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

try {
   db.products.insertOne(
       { "item": "envelopes", "qty": 100, type: "Self-Sealing" },
       { writeConcern: { w : "majority", wtimeout : 100 } }
   );
} catch (e) {
   print (e);
}

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

WriteConcernError({
   "code" : 64,
   "errInfo" : {
      "wtimeout" : true
   },
   "errmsg" : "waiting for replication timed out"
})

See also

To insert multiple documents, see db.collection.insertMany()