When adding many items to a database, you can choose if they should be saved one by one in order or all at once without order. This helps control speed and error handling.
Ordered vs unordered inserts in MongoDB
db.collection.insertMany(documents, { ordered: true|false })ordered: true means insert documents one by one in order. If one fails, stop.
ordered: false means try to insert all documents, even if some fail.
db.users.insertMany([{name: 'Alice'}, {name: 'Bob'}], { ordered: true })db.users.insertMany([{name: 'Alice'}, {name: 'Bob'}], { ordered: false })This tries to insert three products. The third has a duplicate _id which causes an error. Because ordered is true, insertion stops at the error, so only the first two are inserted.
db.products.insertMany([
{ _id: 1, name: 'Pen' },
{ _id: 2, name: 'Pencil' },
{ _id: 1, name: 'Eraser' }
], { ordered: true })Using ordered: false can be faster because MongoDB tries all inserts at once.
Errors in unordered inserts do not stop the process, so you must check which inserts failed.
Duplicate keys cause errors that affect ordered inserts immediately but only partially affect unordered inserts.
Ordered inserts stop at the first error and keep the order.
Unordered inserts try all inserts even if some fail, which can be faster.
Choose based on whether you want strict order and error stopping or speed and partial success.