Question

I am seeing several others questions but any of this solves my problem.

How Can I do this:

UPDATE table SET fiel1 = 'a', field2 = 'b', field3 = 'c' WHERE id='111'

in MongoDB using java driver?

Was it helpful?

Solution

First of all, I think you need to understand how the Mongo shell script should look like. Your SQL-like query would translate into the following:

db.table.update({id : '111'},{$set : {fiel1 : 'a', field2 : 'b', field3 : 'c'}})

Using the Java driver, you will need something like the following:

//obtain the collection object:
DBCollection coll = db.getCollection("table"); //I assume you create your DB-typed db object before

//query DB Object
DBObject query = new BasicDBObject("id", "111");

//nested DB Object of update object
DBObject setObj = new BasicDBObject();
setObj.put("fiel1", "a");
setObj.put("field2", "b");
setObj.put("field3", "c");

//update DB Object
DBObject update = new BasicDBObject("$set", setObj);

coll.update(query, update);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top