I just traced an annoying bug that is mostly racing. For the sake of argument, it allows you to use a very simple document structure, for example { _id : 'XXX', amount : 100 }.
Hundreds of these documents exist inside the collection, and several authors turn to them, who are effectively trying to reduce the amount by any value, but not lower than 0. Currently, this is done with two requests:
- The first query determines the current amount.
- The second query is launched only if the amount is greater than the value to subtract and reduce the current amount.
This, of course, tends to lead to confusion when multiple threads do this at the same time. But is there a way to do this in an atomic operation? I could not find anything like the operation test-and-setin the documents.
If necessary: the code that performs these operations is server-side JavaScript that works with multiple instances of Node.js and the mongodbnpm package .
source
share