I have a collection of messages:
{
messageid: ObjectId
userid: ObjectId
message: string
isread: true|false
}
and a collecti
No, unfortunately this isn't possible. MongoDB only supports atomic operations within the scope of a single document. There's no way to perform a transactional operation across multiple documents, even if they're in the same collection.
You cannot remove documents from two collections at the same instant. What you can do is use a findAndModify() to remove a document so you get its exact state before it was deleted. This will take care of your unread count problem.
MongoDB is very fast, so if your site is not high load you could simply recalculate the total number of messages and the total number of messages read on every request. Only put an index on isread. Count seems to be very fast, even on a large volume of data.
In fact, your total and unread fields are simply caches. Do you really need it ?
There is a question on a similar problem here : MongoDB: Calling Count() vs tracking counts in a collection
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.
You could do this with trigger in sql. But in mongo, there is no trigger.
You can perform operation on one of the document and check for LastErrorMessage on that operation by setting SafeMode.True
Then if no error then update the second collection.
Currently there is no way to do this in atomic way.
If there is, I would have used in my project. I needed that functionality too.