Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb's $set equivalent in its java Driver

Tags:

Is there a way in which I can modify the value of one of the keys in MongoDb via its Java Driver. I tried out the following:

someCollection.update(DBObject query, DBObject update); someCollection.findAndModify(DBObject query, DBObject update); 

But both the functions completely replace the queried document with the updated document. What is the way to update only one of the value of a particular key as in the case of using $set in the mongo shell.(apart from making a completely new Document with all fields copied and one of the fields updated).

like image 318
aditya_gaur Avatar asked Feb 09 '11 10:02

aditya_gaur


People also ask

What is BSON filter?

static Bson. elemMatch(String fieldName, Bson filter) Creates a filter that matches all documents containing a field that is an array where at least one member of the array matches the given filter. static <TItem> Bson. eq(String fieldName, TItem value)

How do I save a list in MongoDB?

DBObject saveObject = new BasicDBObject(). append("$push", dbBasicListOfCars); collection. (car). save(saveObject);


1 Answers

BasicDBObject carrier = new BasicDBObject(); BasicDBObject query = new BasicDBObject(); query.put("YOUR_QUERY_STRING", YOUR_QUERY_VALUE);  BasicDBObject set = new BasicDBObject("$set", carrier); carrier.put("a", 6); carrier.put("b", "wx1");         myColl.updateMany(query, set); 

This should work, the answer which is accepted is not right above.

like image 200
Yekmer Simsek Avatar answered Nov 09 '22 17:11

Yekmer Simsek