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.
The insertOne method adds exactly one document to a collection and returns an acknowledgment containing the new _id:
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:
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.
When you have several documents, insertMany is far more efficient than looping over insertOne because it sends one round trip to the server:
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(...) } }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:
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 errorAn 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.
With data in the database, the next lesson teaches you how to read it back using find() and its powerful filtering and projection options.