简体   繁体   中英

Unable to update Inner Arraylist object using Mongodb Java Driver

I have below document structure in mongodb database:

{
    "_id" : ObjectId("52ec7b43e4b048cd48499b35"),
    "eidlist" : [
        {
            "eid" : "64286",
            "dst" : NumberLong(21044),
            "score" : 0
        },
        {
            "eid" : "65077",
            "dst" : NumberLong(21044),
            "score" : 0
        }
    ],
    "src" : NumberLong(21047)
}

I would like to update score field of first object using Java-mongodb driver: I tried following code but it is not working :( :

  DBObject update_query=new BasicDBObject("src", key).append("eidlist.eid", e.getEdgeid());
  DBObject data=new BasicDBObject("$set",new BasicDBObject("eidlist.score",100));
 coll.update(update_query, data);

Please help me to solve this problem..I have checked all the parameter which I have passed to update function.I think something wrong with the update logic :(

You were close. You omiited the positional operator from the update. Edit your code as shown.

DBObject data=new BasicDBObject("$set",new BasicDBObject("eidlist.$.score",100));

Solution for this problem is:

DBObject data=new BasicDBObject("$set",new BasicDBObject("eidlist.$.score",""+100));

Ensure data type of every field used in the update query.It should be compatible with what we have stored in the mongodb :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM