Chris Covert
Chris Covert

Reputation: 2834

MongoDB and Java: What's wrong with my update?

I'm using MongoDB with the Java driver and have a Collection 'Questions' with the following format for each entry:

{
    "question" : "How are you?",
    "category" : "personal",
    "isTrain"   : true,
    "processed" : true
}

What I want to do is take every entry with both "processed" and "isTrain" equal to true, and I want to set their "processed" value to false. The code in which I'm trying to use for this is:

public void markUnprocessed(boolean isTrain) {
    BasicDBObject queryObj = new BasicDBObject();
    queryObj.put("processed", true);
    queryObj.put("isTrain",   isTrain);

    BasicDBObject updateObj = new BasicDBObject();
    updateObj.put("processed", false);

    collection.updateMulti(queryObj, updateObj);
}

Calling this function from my code seems to have no effect, and I'm not sure why. Any help on the matter would be greatly appreciated.

Thanks,
Chris Covert

Upvotes: 1

Views: 395

Answers (1)

ajg
ajg

Reputation: 369

You need to do a partial using $set, not a full update. With current statement you would be losing all the other fields.

BasicDBObject updateObj = new BasicDBObject();
updateObj.put("$set", new BasicDBObject("processed", false));

Also note that you should turn on safe writes (using WriteConcern.SAFE) so that your app gets notified of any error from server.

Upvotes: 2

Related Questions