在MongoDB中更新(增加)子文档中的值

4
如果我有一个MongoDB集合,其中包含文档和子文档,如下所示: enter image description here 如果我想在每次调用该方法时将“damage”增加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”?

items.damage 是正确的方法。所有内容都从文档的根目录中获取。 - Sammaye
1个回答

8

不是这样的。如果你想要增加与subDocID匹配的items数组元素的damage值,你需要使用$inc操作符和$定位操作符来识别该元素。所以应该是这样的:

"items.$.damage"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接