我有一个 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/