MongoDB Insert
There are two methods for adding documents to a collection:
| Method | Inserts | Returns |
|---|---|---|
insertOne(document) |
one document | { acknowledged, insertedId } |
insertMany([documents], options) |
an array of documents | { acknowledged, insertedIds } |
If the collection doesn't exist, the first insert creates it.
insertOne
const result = db.products.insertOne({
_id: 21,
name: 'Cold Brew Concentrate',
category: 'coffee',
price: 14,
stock: 30,
tags: ['cold', 'ready-to-drink']
});
print(result);
print(db.products.findOne({ _id: 21 }));{ acknowledged: true, insertedId: 21 }
{
_id: 21,
name: 'Cold Brew Concentrate',
category: 'coffee',
price: 14,
stock: 30,
tags: [ 'cold', 'ready-to-drink' ]
}
The result echoes the _id of the new document. In real applications you usually let MongoDB generate it; then insertedId is the only way to learn it:
const { insertedId } = db.products.insertOne({ name: 'Mystery Blend' });
// insertedId is something like ObjectId('6650f3e2a1b2c3d4e5f60718')insertMany
Pass an array to insert several documents in one round trip to the server. This is much faster than calling insertOne in a loop:
const res = db.reviews.insertMany([
{ _id: 1, productId: 3, customerId: 1, stars: 5 },
{ _id: 2, productId: 3, customerId: 5, stars: 4 },
{ _id: 3, productId: 12, customerId: 7, stars: 5 }
]);
print(res.insertedIds);
print(db.reviews.countDocuments());{ '0': 1, '1': 2, '2': 3 }
3
insertedIds maps each position in your array ('0', '1', …) to the _id that was stored.
Duplicate keys
_id must be unique. Inserting a document with an existing _id fails with error E11000, and nothing is written. The error object carries the code and the offending key:
try {
db.products.insertOne({ _id: 1, name: 'Copy of Espresso Beans' });
} catch (err) {
print(err.name, err.code);
print(err.keyValue);
}
print(db.products.findOne({ _id: 1 }).name);MongoServerError 11000
{ _id: 1 }
Espresso Beans
The full err.message reads E11000 duplicate key error collection: shop.products index: _id_ dup key: { _id: 1 }, naming the database, collection and index involved.
Ordered vs unordered insertMany
By default insertMany is ordered: it inserts documents one after another and stops at the first error. Documents before the error stay inserted; documents after it are skipped. With { ordered: false } the server tries every document and reports all the errors at the end:
const batch = [
{ _id: 'a', n: 1 },
{ _id: 'b', n: 2 },
{ _id: 'a', n: 3 }, // duplicate!
{ _id: 'c', n: 4 }
];
try { db.ordered.insertMany(batch); } catch (err) { print('ordered error:', err.code); }
print('ordered: ', db.ordered.find().toArray().map(d => d._id));
try { db.unordered.insertMany(batch, { ordered: false }); } catch (err) { print('unordered error:', err.code); }
print('unordered:', db.unordered.find().toArray().map(d => d._id));ordered error: 11000
ordered: [ 'a', 'b' ]
unordered error: 11000
unordered: [ 'a', 'b', 'c' ]
In the ordered case 'c' was never inserted; in the unordered case only the duplicate was rejected.
Tip: Use
ordered: falsefor bulk imports where one bad record shouldn't block the rest, and the default ordered mode when later documents depend on earlier ones.
Documents don't need the same shape
Nothing stops you from inserting documents with different fields into one collection. Here a gift card has no stock but has a value:
db.products.insertOne({ _id: 22, name: 'Gift Card', category: 'merch', price: 25, value: 25, digital: true });
db.products.find({ category: 'merch' }).forEach(p => print(p));{
_id: 20,
name: 'Travel Mug',
category: 'merch',
price: 16,
stock: 25,
tags: [ 'reusable' ],
rating: 4.3
}
{
_id: 22,
name: 'Gift Card',
category: 'merch',
price: 25,
value: 25,
digital: true
}
Common mistakes
- Passing several documents to
insertOne.insertOne(a, b)inserts onlya(the second argument is options). UseinsertMany([a, b]). - Forgetting the array.
insertMany({ … })throws an error: it needs an array, even for one document. - Re-running an import script. With explicit
_ids, the second run fails with E11000. Use upserts (Upserts) when a script must be repeatable.
Test yourself
An ordered insertMany of 5 documents fails on the 3rd with a duplicate key. How many documents were inserted?
- 0
- 2
- 4
- 5
What does the error code 11000 mean?
- Document too large
- Duplicate key
- Validation failed
- Collection not found
How do you find out the generated _id of a document inserted with insertOne?
- Read
result.insertedId - Call
db.lastId() - It is always 1
- Query the newest document