MongoDB: 更新文档中的字典
MongoDB: update dictionary in document
我有一个 MongoDB 文档,可以在字典中保存某些事物的出现次数:
{
"id" : 1,
"occurrences" : {
"1" : 1,
"2" : 5,
"17" : 1,
"35" : 4
}
}
我现在想添加或更新一些条目,例如将“12:3”添加到出现次数中,或者将“17”的出现次数更新为 2,所以我想举个例子添加 {"12":3} 和 {"17":2} 到这个字典。
这让我发疯,因为我根本无法让它工作。我可以使用数组等等,但我真的很想在这个特定的设计中使用它。关于如何解决这个问题的任何想法?我用 $set 和 $each 等尝试了很多不同的东西。
从mongoDb website看"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" }})
我编写了一个函数将字典转换为新字典,它只更新该字典中的字段:
def convert_2_dict_mongodb(obj):
result = {}
for key, val in obj.items():
if not isinstance(val, dict):
result[key] = val
continue
for sub_key, sub_val in val.items():
new_key = '{}.{}'.format(key, sub_key)
result[new_key] = sub_val
if not isinstance(sub_val, dict):
continue
result.update(convert_2_dict_mongodb(result))
if new_key in result:
del result[new_key]
return result
示例:
abc = {
'a': 1,
'b': {
'x': 1,
'y': 2,
'z': {
'g': 1,
'h': {
'e': [1, 2, 3]
}
}
},
'h': {
'a': [1, 2, 3]
}
}
收件人:
{'h.a': [1, 2, 3], 'b.x': 1, 'b.z.h.e': [1, 2, 3], 'b.z.g': 1, 'a': 1, 'b.y': 2}
我有一个 MongoDB 文档,可以在字典中保存某些事物的出现次数:
{
"id" : 1,
"occurrences" : {
"1" : 1,
"2" : 5,
"17" : 1,
"35" : 4
}
}
我现在想添加或更新一些条目,例如将“12:3”添加到出现次数中,或者将“17”的出现次数更新为 2,所以我想举个例子添加 {"12":3} 和 {"17":2} 到这个字典。 这让我发疯,因为我根本无法让它工作。我可以使用数组等等,但我真的很想在这个特定的设计中使用它。关于如何解决这个问题的任何想法?我用 $set 和 $each 等尝试了很多不同的东西。
从mongoDb website看"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" }})
我编写了一个函数将字典转换为新字典,它只更新该字典中的字段:
def convert_2_dict_mongodb(obj):
result = {}
for key, val in obj.items():
if not isinstance(val, dict):
result[key] = val
continue
for sub_key, sub_val in val.items():
new_key = '{}.{}'.format(key, sub_key)
result[new_key] = sub_val
if not isinstance(sub_val, dict):
continue
result.update(convert_2_dict_mongodb(result))
if new_key in result:
del result[new_key]
return result
示例:
abc = {
'a': 1,
'b': {
'x': 1,
'y': 2,
'z': {
'g': 1,
'h': {
'e': [1, 2, 3]
}
}
},
'h': {
'a': [1, 2, 3]
}
}
收件人:
{'h.a': [1, 2, 3], 'b.x': 1, 'b.z.h.e': [1, 2, 3], 'b.z.g': 1, 'a': 1, 'b.y': 2}