【问题标题】:How to handle DuplicateKeyError in MongoDB (pyMongo)?如何处理 MongoDB (pyMongo) 中的 DuplicateKeyError?
【发布时间】:2017-11-11 17:50:43
【问题描述】:

谁能告诉我如何在MongoDB中处理DuplicateKeyError

我正在编写一个 python 脚本,我将几个文档从两个不同的集合移到第三个集合中。由于有一些相同的文档(具有相同的 ObjectId),这两个集合之间存在少量重叠。这将导致以下结果:

DuplicateKeyError: E11000 重复键错误集合:admin.collection_test index: id dup key: { : ObjectId('593a920b529e170d4b8fbf72') }

为了摆脱我使用的错误:

try:
    do something
except pymongo.errors.DuplicateKeyError:
    pass

我希望通过使用“try-except”将所有非交叉文档移动到第三个集合,但是一旦出现第一个重叠(集合中已经存在的文档),脚本就会平静地停止运行。 非常感谢任何帮助!

【问题讨论】:

  • 您的 ObjectId 已存在此集合的另一个文档

标签: python mongodb pymongo database


【解决方案1】:

如果您要遍历文档,请尝试使用 continue 而不是 pass

for doc in documents:
    try:
        # insert into new collection
    except pymongo.errors.DuplicateKeyError:
        # skip document because it already exists in new collection
        continue

【讨论】:

  • 这应该是基于原始帖子代码示例的公认答案。
【解决方案2】:
for doc in documents:
    client.update_one({'_id': doc['_id']}, doc, upsert=True)

您可以将 update_one 与 upsert=True 一起使用。如果 doc 已经存在,这将使用新 doc 更新 doc,否则它会创建新 doc。

【讨论】:

    【解决方案3】:

    连接到数据库

    connection = pymongo.MongoClient("192.168.2.202", 27017)
    

    创建数据库

    database = connection['my_database']
    

    创建收藏

    collection = database['my_collection']
    

    在集合中插入文档

    url="http://some/api/url/path/?format=json"
    data = {
        '_id': url,
        'timestamp': datetime.datetime.now(),
        'data': {
            'XX': 1,
            'YY': 2,
            'ZZ':  3
        }
    }
    

    避免重复 - 如果相同 ID 不存在,这将创建新文档

    collection.update_one({'_id': url},  {"$set": data}, upsert=True)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-27
      • 2020-07-13
      • 2021-03-08
      • 1970-01-01
      • 2022-11-04
      • 2017-02-11
      • 1970-01-01
      • 2015-08-22
      相关资源
      最近更新 更多