Overwriting a collection in mongoDB (involving remove + bulk save) . How to make sure this is performed as transaction?
mongodb, transactions
Solution
If your collection isn't sharded you could:
- Rename the original collection.
- Create a new collection using the original name.
- Populate the new collection.
- If all went well, drop the original collection, otherwise drop the new collection and rename the original one back to the original name.
Problem
In some situations I need to completely overwrite a specific MongoDB collection by doing: - `db.collection.remove()` - `db.collection.insert(doc)` multiple times. What if 1. succeeds but somewhere 2. fails? Is there a way to do a rollback when this fails? Any other way to go about this?