Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating value of a subfield in MongoDB with Java driver?

Tags:

java

mongodb

I've quite new to MongoDB and it's Java driver.
I need to update the value of a subfield, but I can't find any examples online.

The document:

{
    "_id" : ObjectId("45678942342"),
    "user" : "me",
    "aStruct" : {
        "subfield_1" : true,
        "subfield_2" : true
    }
}

How do I update the value of subfield subfield_1 to false, for every document that has user = me ?


Thank you.

like image 812
thedp Avatar asked Dec 23 '13 12:12

thedp


1 Answers

You can do it as follows :

db.collection.update({user : "me"},{$set:{"aStruct.subfield_1" : false}}, false, true)

In Java you can do it as follows :

DBCollection coll = // Define your collection here

DBObject query = new BasicDBObject();
query.put("user", "me");

DBObject updateObj = new BasicDBObject();
updateObj.put("aStruct.subfield_1", false);

coll.updateMulti(query, new BasicDBObject("$set", updateObj));

For more information read the following document.

  • Update document in MongoDB
like image 79
Parvin Gasimzade Avatar answered Oct 17 '22 00:10

Parvin Gasimzade