insertOne() (Insert Single)
Last updated: 2026-10-09
insertOne() (Insert Single)
insertOne() inserts a single document into a collection. If the document has no _id, MongoDB auto-generates an ObjectId. The result includes insertedId and acknowledged. It is the most direct single-document write, at the cost of one round trip (unlike insertMany()).
| Category | Write |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
db.<collection>.insertOne(<document>, { writeConcern: <options> })
⚙️ Parameters
| document | The BSON document to insert; may contain nested fields and arrays. |
|---|
Returns:WriteResult: { acknowledged, insertedId }
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// insertOne: insert a single user
db.users.insertOne({
name: "Alice",
age: 21,
address: { city: "Beijing" }
})
Output:
{
acknowledged: true,
insertedId: ObjectId("64c8a1b2f3d4e5a6b7c8d9e0")
}
📌 Notes
- ObjectId auto-generated when _id is absent
- Document size limit: 16MB (BSON)
- Duplicate _id throws DuplicateKeyError (unique index)
- Write concern defaults to acknowledged: true
🏷️ Related Tags
💡 Related Cases
Databases and Collections: Namespace Management in MongoDB
Inserting Documents: A Detailed Explanation of `insertOne` and `insertMany`
📚 Related Tutorials
❓ FAQ
QCan insertOne insert an array?
ANo — the top level must be a document (object). Arrays are fine as field values inside the document.
QWhat happens if I omit _id in insertOne?
AMongoDB auto-generates an ObjectId for _id. You may provide your own _id, but it must be unique within the collection or a duplicate key error is raised.
QCan I specify writeConcern with insertOne?
AYes, pass options like { writeConcern: { w: 'majority' } } as the second argument to control acknowledgement level; otherwise the collection or session setting applies.