将多个文档插入空集合,如果 mongodb 已存在具有相同键的文档,则更新
问题描述:
我有这个字典列表 json_data
json_data = [
{
"CODE": "018906",
"X": "29813.66349",
"Y": "28697.520760000003"
},
{
"CODE": "018907",
"X": "30041.8389",
"Y": "28602.98724"
},
{
"CODE": "018910",
"X": "31966.120789999997",
"Y": "29115.75337"
},
]
我有这个 mongodb 集合 code_col
.当集合为空时,我想将 json_data
插入集合 code_col
中.下次可能会有一个新的json_data
,如果keyCODE
相同,应该更新文档而不是插入.
I have this mongodb collection code_col
.
I want to insert json_data
into collection code_col
when the collecion is empty. There may be a new json_data
next time and if the key CODE
is the same, the document should be updated instead of inserted.
我使用的是 python 3.7、pymongo、mongodb 4.2.7.
I am using python 3.7, pymongo, mongodb 4.2.7.
答
您只需要将 upsert
标志设置为 True
.
You just need to set the upsert
flag as True
.
for j in json_data:
db.code_col.update_one({'CODE': j['CODE']},
{'$set': {'X': j['X'], 'Y': j['Y']}},
upsert=True)
更新:通过使用 bulk_write
方法,我们可以在一定程度上减少此操作的时间.
Update: By using bulk_write
method we can somewhat reduce the time for this operation.
from pymongo import UpdateOne
requests = []
for j in json_data:
requests.append(UpdateOne({'CODE': j['CODE']},
{'$set': {'X': j['X'], 'Y': j['Y']}},
upsert=True))
db.code_col.bulk_write(requests)