如果我有一个包含文档和子文档的 MongoDB 集合,如图所示:
并且,如果我想在每次调用该方法时将“伤害”增加 1:
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);
}
问题:我指的是“damage”还是“items.damage”?
最佳答案
都没有。如果您只想使用匹配的 subDocID
增加 items
数组元素的 damage
值,您需要使用 $
positional operator向 $inc
运算符标识该元素。所以它是:
"items.$.damage"
关于java - 更新(递增)MongoDB 子文档中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12536644/