Search code examples
mongodbmongodb-querymongo-java

update BasicDbList element from java


I have a BasicDbObject like the following :

{
    "_id" : ObjectId("57060562ea9bcdfgs50ffdc7"),
    "name" : "g3",
    "detaillist" : [
        {
            "code" : "123",
            "School" : "LDC",
            "Friend" : "Archana"
        },
        {
            "code" : "456",
            "School" : "FWS",
            "Friend" : "Prapth"
        }
    ]
}

How do I update the "school" field of the object which has "code" = "456" from Java (com.mongodb) ?


Solution

  • You would need to use the $set and the positional $ operators in your update to correctly identify the array element since it acts as a placeholder for the first element that matches the query document, and the array field must appear as part of the query document:

    Mongo Shell

    db.collection.update(
        { "detailist.code": "456"},
        {
            "$set": { "detailist.$.School": "foo" }
        }
    )
    

    The following code replicates the above mongo shell query in Java:

    public class JavaUpdateArrayElement {
        public static void main(String args[]) throws UnknownHostException {
    
            MongoClient mongo = new MongoClient();
            DB db = mongo.getDB("databaseName");
    
            DBCollection coll = db.getCollection("test");
    
            /*
                MONGO SHELL : 
                db.test.update(
                    { "detailist.code": "456"},
                    {
                        "$set": { "detailist.$.School": "foo" }
                    }
                )
            */
    
            // build the query { "detailist.code": "456"}
            BasicDBObject query = new BasicDBObject("detailist.code", "456");
    
            // build the update document
            BasicDBObject data = new BasicDBObject();
            data.put("detailist.$.School", "foo");
    
            BasicDBObject update = new BasicDBObject();
            update.put("$set", data);
    
            // run the update operation
            coll.update(query, update);     
    
        }
    }