0
0
MongoDBquery~5 mins

Ordered vs unordered inserts in MongoDB

Choose your learning style9 modes available
Introduction

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.

When you want to stop adding items as soon as one item causes an error.
When you want to add all items even if some cause errors.
When you need to keep the order of items exactly as given.
When you want faster insertion and can accept some errors.
When importing large lists of data where some entries might be duplicates.
Syntax
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.

Examples
Insert users in order. If 'Alice' fails, 'Bob' won't be inserted.
MongoDB
db.users.insertMany([{name: 'Alice'}, {name: 'Bob'}], { ordered: true })
Try to insert both users. If 'Alice' fails, still try to insert 'Bob'.
MongoDB
db.users.insertMany([{name: 'Alice'}, {name: 'Bob'}], { ordered: false })
Sample Program

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.

MongoDB
db.products.insertMany([
  { _id: 1, name: 'Pen' },
  { _id: 2, name: 'Pencil' },
  { _id: 1, name: 'Eraser' }
], { ordered: true })
OutputSuccess
Important Notes

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.

Summary

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.