insertOne()
insertOne adds a single document to a collection and tells you the new _id.
In this page:
Syntax
db.collection_name.insertOne({ field1: value1, field2: value2 })
insertOne()
db.collection.insertOne(document) inserts one document, creating the collection if needed.
If you do not supply an _id, MongoDB generates an ObjectId. The result reports acknowledged and insertedId.
Inserting a duplicate _id raises a duplicate key error.
Note:
Supply your own _id when you have a natural unique key.
Example: insertOne()
test> db.users.insertOne({ _id: 1, name: "Ada", age: 36 })
{ acknowledged: true, insertedId: 1 }
test> db.users.insertOne({ _id: 2, name: "Bob", age: 25, city: "Oslo" })
{ acknowledged: true, insertedId: 2 }
test> db.users.find()
[
{ _id: 1, name: 'Ada', age: 36 },
{ _id: 2, name: 'Bob', age: 25, city: 'Oslo' }
]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Expecting insertOne to update an existing document
- Forgetting the collection is created automatically
- Ignoring duplicate key errors
Chapter Summary
- insertOne adds one document
- _id is generated if missing
- Result has acknowledged and insertedId
- Duplicate _id raises an error
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: