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

编程入门 行业动态 更新时间:2024-10-24 00:17:44
本文介绍了在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中更新(递增)子文档中的值

本文发布于:2023-11-22 18:38:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618552.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文档   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!