Question

I try to rewrite this mongodb query (that works in command line):

db.projects.update({"tools.name" : "gitlab"}, {"$set" : {"tools.$.status" : "error"}})

in java:

DBObject queryUpdate = new BasicDBObject("tools.name", "gitlab");
queryUpdate.put("$set", new BasicDBObject("tools.$.status", "error"));
projects.update(null, queryUpdate, false, true);

I need to update every status if the tools name is "gitlab".

My collection looks like this (I put only one document for testing):

[{
_id: {
    $oid: "531f0e4dd14c366cef214fe7"
},
tools:[
    {
        name: "gitlab",
        url: "https://url/",
        status: "success",
        selected: true
    }, {
        name: "svn",
        url: "https://url/",
        status: "error",
        selected: true
    }]
}]

I think I'm really missing something...

Was it helpful?

Solution

By default, the update query only updates one document (the first matched). You will need to set the multi flag to true.

Also the update query in your statement is incorrect. You should try:

DBObject querySelect = new BasicDBObject("tools.name", "gitlab");
DBObject queryUpdate = new BasicDBObject("$set", new BasicDBObject("tools.$.status", "error"));
projects.update(querySelect, queryUpdate, false, true);

Note: The $ positional operator matches only the first element within the array. So, if you had multiple elements within the "tools" array with name="gitlab", only the first element will be updated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top