First let me translate your Java code into a shell script so that people can read it:
db.coll.update({key: k1}, {$inc:{balance:10}}) db.coll.update({key: k2}, {$inc:{balance:-10}})
Now, the reason you can never do this in one update is because there is no way to provide a unique update proposal for each document. You can distribute your updates so you can do it (pseudo):
set1 = getAllKeysForBalanceIncrease(); set2 = getAllKeysForBalanceDecrease(); db.coll.update({key:{$in:set1}}, {$inc:{balance:10}}, false, true) db.coll.update({key:{$in:set2}}, {$inc:{balance:-10}}, false, true)
In other words, you can update several documents in one atomic record, but the update operation will be static for all documents. Thus, combining all documents that require the same update is your only optimization path.
The $ in clause can be compiled in Java via:
ObjectId[] oidArray = getAllKeysEtc(); query = new BasicDBObject("key", new BasicDBObject("$in", oidArray));
source share