如何使用pymongo为mongo条目搜索和更新字典列表中的值



我有类似的mongo条目

{
"_id" : ObjectId("5fdc78778adbdedd17ce6ff3"),
"solution_id" : "5fd6e275a675f2000134b243",
"versions" : [
{
"local" : 2,
"s3" : null
}
]
}

我需要搜索并更新CCD_ 1关键字的值为"strong";abc"。如何使用pymongo?

您需要一个"路线";可以使用点号来确定对象结构中需要更新的元素;在您的情况下,这是versions.0.s3。如果你很乐意在python中这样做,并调整你的代码,它会看起来像:

for i in cursor1:
for index, j in enumerate(i.get('versions', [])):
if j.get('local') == 2:
db.mycollection.update_one({'_id': i.get('_id')}, {'$set': {f'versions.{index}.s3': 'abc'}})

您可以使用$位置操作符在单个更新操作中完成整个操作。NB这只更新在local == 2上找到的第一个匹配;python示例将更新数组中所有匹配的项。

db.mycollection.update_one({'_id': ObjectId(document_id), 'versions.local': 2}, {'$set': {'versions.$.s3': 'abc'}})

选项1

item_id = ObjectId("5fdc78778adbdedd17ce6ff3")
db.collection.update({'_id': item_id}, {'$set': {'versions.$.s3': 'abc'}})

选项2

query = {}
item_id = ObjectId("5fdc78778adbdedd17ce6ff3")
items = db.collection.find({'_id': item_id})
for i, _ in enumerate(items):
query[f'versions.{i}.s3'] = 'abc'
db.collection.update({'_id': item_id}, {'$set': query})

最新更新