db.collection.insertOne() (original) (raw)
db.collection.insertOne()
Inserts a single document into a collection.
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 the inserted document. |
---|
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, seeUnsupported 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
The insertOne() method has the following form:
db.collection.insertOne(
<document>,
{
writeConcern: <document>
}
)
The insertOne() method takes the following parameters:
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. .. include:: /includes/extracts/transactions-operations-write-concern.rst |
If the collection does not exist, then theinsertOne() method creates the collection.
If the document does not specify an _id field, then mongodwill add the _id
field and assign a uniqueObjectId() for the document before inserting. Most drivers create an ObjectId and insert the _id
field, but themongod 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.
insertOne() is not compatible withdb.collection.explain().
On error, db.collection.insertOne() throws either a writeError
or writeConcernError
exception.
If your collection uses schema validation and has validationAction
set toerror
, inserting an invalid document throws a MongoServerError
and db.collection.insertOne()
fails.
db.collection.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, thedenormalized 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 alsoProduction 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.
See also:
Do not explicitly set the write concern for the operation if run in a transaction. To use write concern with transactions, seeTransactions and Write Concern.
If a db.collection.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.
In the following example, the document passed to theinsertOne() 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.
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 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
}
})
Given a three member replica set, the following operation specifies aw
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 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"
}
}
})
See also:
- To insert multiple documents, seedb.collection.insertMany()
- WriteResult.writeConcernError