MongoDB更新集合记录选update_one还是update_many?报错求解
错误原因
- 你的代码中循环遍历单条数据的key时,
key本身就是字段名(字符串类型,比如Sector、RKK_T),你调用key.keys()[i]相当于尝试对字符串取keys属性,自然会报错 - 查询条件写死为
{'Sector': 'Sector'},只能匹配到Sector值为字符串Sector的文档,完全不符合按Sector字段匹配业务数据的需求 - 不需要逐字段执行更新,MongoDB的
$set支持直接传入完整的字段字典批量更新多个字段
正确实现方式
方式1:循环单条更新(适合数据量较小的场景)
from pymongo import MongoClient import datetime # 假设你已经完成MongoDB连接,collection为已初始化的集合对象 for item in data: # 按Sector字段构造匹配条件 query = {"Sector": item["Sector"]} # 构造待更新字段,移除不需要覆盖的_id(新数据的_id为字符串,库中为ObjectId类型,无需覆盖) update_fields = item.copy() update_fields.pop("_id") # 执行更新:upsert=True表示匹配不到则插入新文档 collection.update_one( query, {"$set": update_fields, "$currentDate": {"lastModified": True}}, upsert=True )
方式2:批量更新(适合数据量较大的场景,性能远高于单条循环)
使用bulk_write一次提交所有更新请求,减少网络IO开销:
from pymongo import MongoClient, UpdateOne import datetime operations = [] for item in data: query = {"Sector": item["Sector"]} update_fields = item.copy() update_fields.pop("_id") operations.append( UpdateOne( query, {"$set": update_fields, "$currentDate": {"lastModified": True}}, upsert=True ) ) # 非空时执行批量操作 if operations: collection.bulk_write(operations)
update_one与update_many的选择说明
- 你的业务场景中每个Sector对应唯一一条数据,使用
update_one即可,只会更新匹配到的第一条文档,符合需求 - 只有当你需要将所有匹配到查询条件的文档全部更新时,才需要使用
update_many
内容的提问来源于stack exchange,提问作者Alexander
相关产品推荐
相关产品推荐

