MongoDB with drivers
This page documents a mongosh method. To see the equivalent
method in a MongoDB driver, see the corresponding page for your
programming language:
Definition
db.collection.insertOne()Inserts a single document into a collection.
Returns: A document containing: A boolean
acknowledgedastrueif the operation ran with write concern orfalseif write concern was disabled.A field
insertedIdwith the_idvalue of the inserted document.
Compatibility
This method is available in deployments hosted in the following environments:
MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
Note
This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.
MongoDB Enterprise: The subscription-based, self-managed version of MongoDB
MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB
Syntax
db.collection.insertOne() has the following
form:
db.collection.insertOne( <document>, { writeConcern: <document> } )
Parameters
insertOne() takes the following
parameters:
Parameter | Type | Description |
|---|---|---|
| document | A document to insert into the collection. |
| 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 Transactions and Write Concern. |
Behaviors
Collection and _id Field Creation
If the collection does not exist, then insertOne() 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.
Explainability
insertOne() is not compatible with
db.collection.explain().
Error Handling
On error, insertOne() throws either a writeError
or writeConcernError exception.
Schema Validation Errors
If your collection uses schema validation and has validationAction set to
error, inserting an invalid document throws a
MongoServerError and insertOne() fails.
Transactions
insertOne() 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.
Collection Creation in Transactions
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.
Write Concerns and Transactions
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.
Oplog Entries
If an insertOne() 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.
Examples
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.
Insert a Document without Specifying an _id Field
The following example inserts a document without an _id field
into the movies collection:
db.movies.insertOne( { title: "Inception", year: 2010, genres: [ "Action", "Sci-Fi" ] } )
{ acknowledged: true, insertedId: "..." }
Because the 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.
Insert a Document Specifying an _id Field
When you specify _id when inserting a document, the _id value
must be unique within the collection. The following example inserts
a document into the movies collection and specifies _id:
db.movies.insertOne( { _id: 10, title: "Inception", year: 2010 } )
{ acknowledged: true, insertedId: 10 }
Inserting a 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.movies.insertOne( { _id: 10, title: "Inception", year: 2010 } ); } 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: sample_mflix.movies index: _id_ dup key: { : 10.0 }", "op" : { "_id" : 10, "title" : "Inception", "year" : 2010 } })
Increase Write Concern
Given a three member replica set, the following operation specifies a
w of majority, wtimeout of 100:
try { db.movies.insertOne( { title: "Arrival", year: 2016 }, { writeConcern: { w : "majority", wtimeout : 100 } } ); } catch (e) { print (e); }
If the acknowledgment takes longer than the wtimeout limit, the following
exception is thrown:
WriteConcernError({ "code" : 64, "errmsg" : "waiting for replication timed out", "errInfo" : { "wtimeout" : true, "writeConcern" : { "w" : "majority", "wtimeout" : 100, "provenance" : "getLastErrorDefaults" } } })