← Back to MongoDB Course | Chapter 2: CRUD — Create | Lesson 1 of 7

insertOne()

insertOne adds a single document to a collection and tells you the new _id.

In this page:

  1. insertOne()
Syntax
javascript
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()

bash
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/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Expecting insertOne to update an existing document
  2. Forgetting the collection is created automatically
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.