我有一个MongoDB文档,该文档将某些事物的出现保存在字典中:
I have a MongoDB document that saves occurrences of some things in a dictionary:
{ "id" : 1, "occurrences" : { "1" : 1, "2" : 5, "17" : 1, "35" : 4 } }我现在想添加或更新一些条目,例如在出现次数上添加"12:3",或将出现次数"17"更新为2,所以举个例子,我想添加{ "12":3}和{"17":2}到此字典. 这让我发疯,因为我根本无法正常工作.我可以使用数组,但我真的很想在特定的设计中使用它.关于如何解决这个问题的任何想法?我用$ set和$ each等尝试了很多不同的东西.
I now want to add or update some entries, for example add a "12:3" to the occurrences, or update the number of occurrences of "17" to 2, so let's say as an example I want to add {"12":3} and {"17":2} to this dictionary. It is driving me crazy because I simply can not get it to work. I could use arrays and all that, but I would really like to have it in this particular design. Any ideas on how to solve this? I tried so many different things with $set and $each and so on.
推荐答案来自 mongoDb网站查看设置嵌入式文档中的字段"
from mongoDb website look at "Set Fields in Embedded Documents"
To specify a <field> in an embedded document or in an array, use dot notation. For the document matching the criteria _id equal to 100, the following operation updates the make field in the details document: db.products.update( { _id: 100 }, { $set: { "details.make": "zzz" } })以您的情况
db.collection.update( {_id:ObjectId("1")}, { $set: { "occurrences.12": "3", "occurrences.17": "2" }})更多推荐
MongoDB:更新文档中的字典
发布评论