Update a few lines in the Java driver from MongoDB

I want to update a few lines in My Collection called Users. Right now I am updating both rows separately, but I want to do the same in a single query.

My current code is:

coll.update(new BasicDBObject().append("key", k1), new BasicDBObject().append("$inc", new BasicDBObject().append("balance", 10))); coll.update(new BasicDBObject().append("key", k2), new BasicDBObject().append("$inc", new BasicDBObject().append("balance", -10))); 

How to make these two separate updates in one statement?

+4
source share
2 answers

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)); 
+3
source

In MongoDB, you do not have transactions that span multiple documents. Only records on a document are atomic. But you can do updates with:

 public WriteResult update(DBObject q, DBObject o, boolean upsert, boolean multi) 

But note that this will not be in the transaction.

-1
source

All Articles