问题
I have this list of dictionaries 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"
},
]
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.
I am using python 3.7, pymongo, mongodb 4.2.7.
回答1:
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)
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)
来源:https://stackoverflow.com/questions/62220625/insert-many-documents-into-empty-collection-update-if-document-with-same-key-al