Insert many documents into empty collection, update if document with same key already exist for mongodb

狂风中的少年 提交于 2020-06-29 04:36:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!