Is there any way to atomically update two collections in MongoDB?

后端 未结 5 1259
轻奢々
轻奢々 2020-12-08 08:45

I have a collection of messages:

{
    messageid: ObjectId
    userid: ObjectId
    message: string
    isread: true|false
}

and a collecti

5条回答
  •  旧巷少年郎
    2020-12-08 09:13

    There are lots of answers here, but I want to fill in all of the blanks here:

    Is there any way to atomically update two collections in MongoDB?

    No. Atomic update of two collections is effectively a transaction. MongoDB does not support transactions across collections or even within a collection.

    MongoDB provides several modifiers that are atomic on a single document. So you can increment several different variables at once ($inc). Though there are some limitations here, you cannot perform two different operations on a single property.

    Is there a way to conditionally change something in one collection based on results of other collection in one shot?

    There are some documents here on atomic updates in general. However, what you really need is a queue and some form of two-phase commit or you need triggers.

    Triggers have not yet been implemented, so it's not really an option in your case.

    There is a possibility that the message will be marked as read in between those actions, then I will decrease "unread" counts incorrectly.

    At this point, you have a couple of different strategies for making this behave with some level of consistency. Frankly, based on your description, you may want to investigate building a simple queue that updates your totals.

提交回复
热议问题