[英]How to modify a field in a nested pymongo dictionary record in python
I have a mongo db with following structure我有一个具有以下结构的 mongo db
{
"_id" : ObjectId("5f59c289fb28ab4476d4578b"),
"data" : [
{
"time" : "10-Sep-2020 11:33:22",
"type" : "Med01",
"id":123
"expdate" : "01-Sep-2021",
"in_stock" "Y"
},
{
"time" : "10-Sep-2020 11:33:22",
"type" : "Med06",
"id":125
"expdate" : "10-Sep-2020",
"in_stock" "N"
},
{
"time" : "10-Sep-2020 11:33:22",
"type" : "LOC1",
"id":103
"expdate" : "10-Sep-2023",
"in_stock" "Y"
}
]
} }
I would like to update the in_stock
field based on the given id
, say for example I need to modify the in_stock
of medicine with id
103
to N
我想根据给定的id
更新in_stock
字段,例如我需要将id
103
的药物in_stock
修改为N
I tried with below and it is working but I won't be knowing the list number ( 2
) in advance.我在下面尝试过,它正在工作,但我不会提前知道列表编号 ( 2
)。
update_one({"_id": id_1}, {'$set': {"data.2.in_stock":'N'}})
I have the value 2
in a variable but not sure how to pass that in the above query.我在变量中有值2
但不确定如何在上面的查询中传递它。 Can someone help?有人可以帮忙吗?
You need to use the $
positional operator .您需要使用$
位置运算符。 Note this will match on the first matching array element only.请注意,这将仅匹配第一个匹配的数组元素。
db.mycollection.update_one({'_id': id_1, 'data.id': 103}, {'$set': {"data.$.in_stock":'N'}})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.