问题描述
我有一组消息:
{
messageid: ObjectId
userid: ObjectId
message: string
isread: true|false
}
以及每个用户的消息计数集合:
and a collection of message counts per user:
{
userid: ObjectId
total: int
unread: int
}
当我从messages"集合中删除一条消息时,我还需要减少counts"集合中的total",并且有条件地(如果messages.isread"==false)也减少unread"字段.
When I delete a message from "messages" collection, I also need to decrease "total" in "counts" collection, and conditionally (if "messages.isread" == false) decrease "unread" field as well.
为此,我需要首先检索消息,检查其isread"字段,然后更新计数.消息有可能在这些操作之间被标记为已读,然后我会错误地减少未读"计数.
For that I need to first retrieve teh message, check its "isread" field, and then update the counts. There is a possibility that the message will be marked as read in between those actions, then I will decrease "unread" counts incorrectly.
有没有一种方法可以根据一次拍摄中其他集合的结果有条件地更改一个集合中的某些内容?
Is there a way to conditionally change something in one collection based on results of other collection in one shot?
推荐答案
这里有很多答案,但我想把这里的所有空白都填上:
There are lots of answers here, but I want to fill in all of the blanks here:
有没有办法原子更新 MongoDB 中的两个集合?
没有.两个集合的原子更新实际上是一个事务.MongoDB 不支持跨集合甚至一个集合内的事务.
No. Atomic update of two collections is effectively a transaction. MongoDB does not support transactions across collections or even within a collection.
MongoDB 提供几个修饰符,它们在单个文档上是原子的.所以你可以一次增加几个不同的变量($inc
).尽管这里有一些限制,但您不能对单个属性执行两种不同的操作.
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.
有没有一种方法可以根据一次拍摄中其他集合的结果有条件地更改一个集合中的某些内容?
这里有一些关于原子更新的文档.然而,你真正需要的是一个队列和某种形式的两阶段提交 或者你需要触发器.
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.
邮件可能会在这些操作之间被标记为已读,然后我会错误地减少未读"计数.
此时,您有几种不同的策略可以使这种行为具有某种程度的一致性.坦率地说,根据您的描述,您可能想要研究构建一个简单的队列来更新您的总数.
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.
这篇关于有没有办法自动更新 MongoDB 中的两个集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!