开发者

Update multiple rows in MongoDB java Driver

I want to update multiple rows in My Collection called "Users". Right now I am updating both the rows seperately but I want to do the same in one query.

My current code:

coll.update(new BasicDBObject().append("key", k1), new BasicDBObject().a开发者_如何学JAVAppend("$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 seperate updates in one statement?


First let me translate your java code to shell script so people can read it :

db.coll.update({key: k1}, {$inc:{balance:10}})
db.coll.update({key: k2}, {$inc:{balance:-10}})

Now, the reason you will never be able to do this in one update is because there is no way to provide a unique update clause per matching document. You could bulk your updates so that you can do this (pseudoish):

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 multiple documents within one atomic write but the update operation will be static for all documents. So aggregating all documents that require the same update is your only optimization path.

The $in clause can be composed in Java through :

ObjectId[] oidArray = getAllKeysEtc();
query = new BasicDBObject("key", new BasicDBObject("$in", oidArray));


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

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

But note, this will not be in a transaction.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜