Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ATOMICally update multiple documents AND return them

In MongoDB, I'm looking for a way to ATOMICally update multiple documents and return all of the updated documents in a single call.

We can do all of the following in MongoDB:

  • Atomically update one document and return the updated document: findAndModify or findOneAndUpdate
  • Atomically update multiple documents: update(...{multi: true} or updateMany
  • Query and return multiple documents: find

I haven't fond a way to update multiple documents and return them all in one call. Is there a way? I'm using Mongoose as the querying package.

like image 879
Daniel Flippance Avatar asked Dec 10 '16 02:12

Daniel Flippance


1 Answers

Atomically update multiple documents: update(...{multi: true} or updateMany

Unfourtantely that is false:

In MongoDB, write operations, e.g. db.collection.update(), db.collection.findAndModify(), db.collection.remove(), are atomic on the level of a single document.


In MongoDB, a write operation is atomic on the level of a single document, even if the operation modifies multiple embedded documents within a single document.

However, you can simulate a transaction to atomically update multiple documents by "using a two-phase commit approach" which is described in detail there.

You may also look at the $isolated operator, which "prevents a write operation that affects multiple documents from yielding to other reads or writes once the first document is written" but it "does not provide “all-or-nothing” atomicity for write operations"

As a summary, it is not possible at mongodb level (nor the driver), but you can simulate it at your application level therefore return what you need.

like image 200
sergiuz Avatar answered Oct 05 '22 11:10

sergiuz