MongoDB:更新文档中的字典

标签 mongodb dictionary upsert

我有一个 MongoDB 文档,它在字典中保存了某些内容的出现:

{
  "id" : 1,
  "occurrences" : {
    "1" : 1,
    "2" : 5,
    "17" : 1,
    "35" : 4
  }
}

我现在想添加或更新一些条目,例如在出现次数中添加“12:3”,或者将“17”的出现次数更新为 2,所以假设我想添加 { "12":3} 和 {"17":2} 到这本字典。 它让我发疯,因为我根本无法让它工作。我可以使用数组和所有这些,但我真的很想在这个特定的设计中使用它。关于如何解决这个问题的任何想法?我用 $set 和 $each 等尝试了很多不同的东西。

最佳答案

来自 mongoDb website查看“在嵌入式文档中设置字段”

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:更新文档中的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29267519/

相关文章:

python - 从 Python 字典 : 中的值中查找键

node.js - Mongoose 中的多文档更新插入

sqlite - 在 Sqlite 3.34 中执行 UPSERT 时出错 - 错误 : near "DO": syntax error

mongodb - 将序列号添加到来自 mongodb 查询的项目

java - MongoDB Java 驱动程序 : autoConnectRetry

python - 如何将 Pandas 数据框列映射到嵌套字典

c++ - 使用 const 键但非 const 值进行映射?

mongodb - 用 $in 更新插入

mongodb - 如何计算Docker容器中的WiredTiger缓存大小?

mongodb - 匿名结构返回空字段值