Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating (incrementing) a value within a sub-document in MongoDB

If I have a MongoDB collection with documents and sub-documents, as illustrated:

enter image description here

And, if I want to increment the "damage" by 1 each time the method is called:

private final static void incrementCount(String docID, String subDocID) {
    BasicDBObject query = new BasicDBObject();
    query.put("_id", docID);
    query.put("items.id", subDocID);
    BasicDBObject incValue = new BasicDBObject("damage", 1); // or "items.damage" ???
    BasicDBObject intModifier = new BasicDBObject("$inc", incValue);
    badgesCollection.update(query, intModifier, false, false, WriteConcern.SAFE);
}

Question: do I refer to "damage" or "items.damage" ?

like image 940
ikevin8me Avatar asked Feb 19 '23 02:02

ikevin8me


1 Answers

Neither. If you want to increment just the damage value for the items array element with the matching subDocID you need to use the $ positional operator to identify that element to the $inc operator. So it's:

"items.$.damage"
like image 194
JohnnyHK Avatar answered Apr 29 '23 01:04

JohnnyHK