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()).

CategoryWrite
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

db.<collection>.insertOne(<document>, { writeConcern: <options> })

⚙️ Parameters

documentThe 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

📚 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏