Inserting Documents

beginner
10 min

Inserting Documents

Writing data is where every MongoDB application begins. In this CodeYourCraft lesson you will master the two core insert methods, insertOne and insertMany, learn how MongoDB assigns ObjectIds, and see how to handle duplicate key errors and ordered versus unordered bulk inserts.

insertOne: Adding a Single Document

The insertOne method adds exactly one document to a collection and returns an acknowledgment containing the new _id:

javascript
use shop db.customers.insertOne({ name: 'Arjun Mehta', email: 'arjun@example.com', loyaltyPoints: 0, joinedAt: new Date() }) // { // acknowledged: true, // insertedId: ObjectId('66a1f0c2e4b0a1b2c3d4e5f6') // }

Because we did not provide an _id, MongoDB generated an ObjectId. You can supply your own _id, such as a product SKU, as long as it is unique within the collection:

javascript
db.products.insertOne({ _id: 'SKU-1001', name: 'USB-C Cable', price: 499 })

If you insert a second document with the same _id, MongoDB raises a duplicate key error (code 11000) and the write is rejected. This uniqueness guarantee is enforced by the automatic index on _id.

insertMany: Bulk Inserts

When you have several documents, insertMany is far more efficient than looping over insertOne because it sends one round trip to the server:

javascript
db.products.insertMany([ { name: 'Webcam 1080p', price: 2999, tags: ['video'] }, { name: 'Desk Lamp', price: 1299, tags: ['home', 'lighting'] }, { name: 'Noise-Cancelling Headphones', price: 8999, tags: ['audio'] } ]) // { acknowledged: true, insertedIds: { '0': ObjectId(...), '1': ObjectId(...), '2': ObjectId(...) } }

Ordered vs Unordered Inserts

By default insertMany is ordered: documents are inserted in array order, and if one fails, everything after it is abandoned. With ordered set to false, MongoDB attempts every document and reports all failures at the end, which is usually what you want for imports:

javascript
db.products.insertMany( [ { _id: 'SKU-1001', name: 'Duplicate!' }, // will fail { _id: 'SKU-2002', name: 'Monitor Arm', price: 3499 } ], { ordered: false } ) // SKU-2002 is still inserted despite the earlier duplicate key error

What Happens During an Insert

An insert does more than copy bytes. MongoDB validates that the document is under 16 MB, adds the _id if missing, updates every index on the collection, and journals the write for durability. By default writes are acknowledged by the server, and in a replica set you can strengthen this with write concerns such as w: 'majority' to wait until most nodes have the data.

Practical Tips

  • Insert dates as Date objects, not strings, so range queries and sorting behave correctly.
  • Store money as integers in the smallest unit (paise, cents) or use NumberDecimal to avoid floating point drift.
  • Batch large imports into chunks of roughly one thousand documents per insertMany call.
  • Let MongoDB generate ObjectIds unless you have a natural unique key like a SKU or ISBN.

Key Takeaways

  • insertOne writes a single document; insertMany writes an array in one round trip.
  • MongoDB auto-generates an ObjectId for _id when you do not supply one.
  • Duplicate _id values trigger error 11000 and reject the write.
  • Use ordered: false for bulk loads that should survive individual failures.
  • Choose proper BSON types for dates and money at insert time.

With data in the database, the next lesson teaches you how to read it back using find() and its powerful filtering and projection options.

Inserting Documents - MongoDB | CodeYourCraft | CodeYourCraft