5

I am learning about mongodb. If I create a bulk write is this transaction all or nothing? I have a scenario where my users can delete who they are friends with.

FRIEND 1  |  FRIEND 2
  User B     USER A
  User A     USER B

For this to happen I need to delete from both bidirectional relationships. For consistency I need these to occur as a all or nothing because I wouldn't want only 1 of the 2 operations to succeed as this would cause bad data. Reading the docs I could not find the answer:

https://docs.mongodb.org/manual/core/bulk-write-operations/

user2924127
  • 6,034
  • 16
  • 78
  • 136
  • 1
    Related: [Are Bulk Operations Written to the Op-Log as a whole?](http://stackoverflow.com/questions/32156700/mongodb-are-bulk-operations-written-to-the-oplog-as-a-whole/32156839#32156839). But anything that succeeds will be written as there is no built in concept of "rollback". Also noting that "un-ordered" operations batches will write every operation that does not error, as opposed to "ordered" where the writes will cease on the first error. – Blakes Seven Dec 05 '15 at 22:37

1 Answers1

8

db.collection.initializeOrderedBulkOp() "If an error occurs during the processing of one of the write operations, MongoDB will return without processing any remaining write operations in the list."

No mention of rollback ops, simply stops inserting the remaining.

db.collection.insert() method "The insert() method, when passed an array of documents, performs a bulk insert, and inserts each document atomically."

you can roll your own . but use acknowledged write concern which would have to be via your chosen driver. shell is acknowledged but perhaps driver is not.

https://docs.mongodb.org/manual/core/write-concern/

try
   insert 1
catch 
  delete

try
   insert 2
catch 
  delete 1
  delete 2
Gabe Rainbow
  • 3,658
  • 4
  • 32
  • 42