本文介绍了在MongoDB中更新(递增)子文档中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个包含文档和子文档的MongoDB集合,如图所示:
If I have a MongoDB collection with documents and sub-documents, as illustrated:
而且,如果我想在每次调用该方法时将损坏"增加1,则:
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); }问题:我是指损坏"还是"items.damage"?
Question: do I refer to "damage" or "items.damage" ?
推荐答案都没有.如果只想增加具有匹配的subDocID的items数组元素的damage值,则需要使用$ 位置运算符,以将该元素标识为$inc运算符.就是这样:
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"更多推荐
在MongoDB中更新(递增)子文档中的值
发布评论