0

I am wondering if the following is achievable in MongoDB. I am building a simple REST API and one of the functionality's it will offer is to update a field in multiple documents using Mongoose and the updateMany() function.

Reading this: https://docs.mongodb.com/manual/core/read-isolation-consistency-recency/#read-uncommitted-and-multiple-document-write

I came to believe that it is not possible to lock-out any reads from happening during the updating of the documents by updateMany(). Is this correct or is it possible to block all read operations when this function is called until it finishes?

SomeDutchGuy
  • 2,249
  • 4
  • 16
  • 42
  • 1
    The very next paragraph in the post you linked suggests using transactions: https://docs.mongodb.com/manual/core/transactions/ – Sergio Tulentsev Nov 13 '19 at 12:38
  • @SergioTulentsev I read that but far as I understand these cannot be used in this context. Unless I am misunderstanding it. – SomeDutchGuy Nov 13 '19 at 12:41
  • 1
    Why do you think transactions can't be used here? – Sergio Tulentsev Nov 13 '19 at 12:42
  • @SergioTulentsev I guess it is due to my lack of understanding how transaction work in MongoDB and me not being able to find any examples that utilize transactions with an isolation level set at serializable. – SomeDutchGuy Nov 13 '19 at 12:47
  • 2
    Transactions are atomic (that is their whole reason to exist). Either all documents are updated, or none are. Your reads won't see half-updated documents, if that's your concern. – Sergio Tulentsev Nov 13 '19 at 12:54
  • @SergioTulentsev that does not mean a read cannot see the updates before all are finished in my knowledge (I need to update to be completely finished before a read is allow to occur). – SomeDutchGuy Nov 13 '19 at 13:10
  • What do you think "atomic" means then, if not this? – Sergio Tulentsev Nov 13 '19 at 13:16
  • There's a difference between "before a read is allowed to occur" and "before a read sees the updated value"? You say you need the former, but I think you merely want the latter. Which is it? – Sergio Tulentsev Nov 13 '19 at 13:23
  • @SergioTulentsev reads should see nothing until all updates are performed. – SomeDutchGuy Nov 13 '19 at 13:29
  • @SergioTulentsev just found that the isolation level is snapshot so updates are not visible outside the context of the session until they are committed. https://www.percona.com/blog/2018/06/25/mongodb-transactions-your-very-first-transaction-with-mongodb-4-0/ – SomeDutchGuy Nov 13 '19 at 13:56

0 Answers0