MongoDB:更新文档中的字典

编程入门 行业动态 更新时间:2024-10-23 05:02:22
本文介绍了MongoDB:更新文档中的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个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:更新文档中的字典

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

发布评论

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

>www.elefans.com

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