将多个文档插入空集合,如果 mongodb 已存在具有相同键的文档,则更新 [英] Insert many documents into empty collection, update if document with same key already exist for mongodb

查看:48
本文介绍了将多个文档插入空集合,如果 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)

这篇关于将多个文档插入空集合,如果 mongodb 已存在具有相同键的文档,则更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆