Are bulk inserts atomic in MongoDB

2019-07-17 05:37发布

问题:

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/

回答1:

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