Geert-Jan
Geert-Jan

Reputation: 18895

Overwriting a collection in mongoDB (involving remove + bulk save) . How to make sure this is performed as transaction?

In some situations I need to completely overwrite a specific MongoDB collection by doing:

  1. db.collection.remove()
  2. 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?

Upvotes: 4

Views: 1691

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311855

If your collection isn't sharded you could:

  1. Rename the original collection.
  2. Create a new collection using the original name.
  3. Populate the new collection.
  4. If all went well, drop the original collection, otherwise drop the new collection and rename the original one back to the original name.

Upvotes: 5

Related Questions