thedp
thedp

Reputation: 8508

Updating value of a subfield in MongoDB with Java driver?

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.

Upvotes: 6

Views: 3860

Answers (1)

Parvin Gasimzade
Parvin Gasimzade

Reputation: 26012

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.

Upvotes: 8

Related Questions