我想更新嵌套文档的记录,我的文档如下所示:
[
{
"_id": "60753fd9b249ad0dfa1eeb48",
"name": "Random Name 1",
"email": "randomname1@zmel.kom",
"likings": [
{
"breakfast": {
"eat": "oats",
"drink": "milk"
}
},
{
"lunch": {
"eat": "beef",
"drink": "pepsi"
}
},
{
"dinner": {
"eat": "steak",
"drink": "champagne"
}
}
]
},
{
"_id": "60753fd9b249ad0dfa1eeb58",
"name": "Random Name 2",
"email": "randomname2@zmel.kom",
"likings": [
{
"breakfast": {
"eat": "cereals",
"drink": "coffee"
}
},
{
"lunch": {
"eat": "salad",
"drink": "hot-water"
}
},
{
"dinner": {
"eat": "biryani",
"drink": "apple juice"
}
}
]
}
]
现在我想更新drink
for的值dinner
,Random Name 2
但我不知道晚餐的索引,它可能在 之上lunch
,也可能在 之下breakfast
。
这是我在 Python 中尝试过的:
oid = data[0] # fetched from flask form
to_be_updated = data[1] # fetched from flask form
update_value = data[2] # fetched from flask form
condition = {"_id" : oid}
update_value = {
"$set" : {
f"likings.{to_be_updated}.drink" : update_value
}
}
response = mongo.db.food.update(condition, update_value)
但我得到的错误是:
pymongo.errors.WriteError: Cannot create field 'dinner' in element <complete element description>
我计划使用的其他策略是,仅匹配 ID,然后likings
通过保持不需要更改的值并更改我想要更改的值来更新。但是这种方法似乎太明显并且在语义上是错误的,因为我正在使用not updating but updating
一种策略,即无缘无故地干扰集合模式。有没有办法做到这一点,或者我应该继续我的想法