【问题标题】:How to prevent duplicates in pymongo如何防止pymongo中的重复
【发布时间】:2025-12-05 17:35:01
【问题描述】:

我正在使用 pymongo "insert_one", 我想防止插入两个具有相同“名称”属性的文档。

  1. 我一般如何防止重复?
  2. 如何为名称等特定属性配置它?

谢谢!

我的代码:

client = MongoClient('mongodb://localhost:8888/db')
db = client[<db>]
heights=db.heights

post_id= heights.insert_one({"name":"Tom","height":2}).inserted_id


try:
    post_id2 = heights.insert_one({"name":"Tom","height":3}).inserted_id

except pymongo.errors.DuplicateKeyError, e:
    print e.error_document

print post_id
print post_id2

输出:

56aa7ad84f9dcee972e15fb7

56aa7ad84f9dcee972e15fb8

【问题讨论】:

    标签: python mongodb pymongo


    【解决方案1】:

    您需要创建一个索引,以确保该名称在该集合中是唯一的

    例如

    db.heights.create_index([('name', pymongo.ASCENDING)], unique=True)
    

    请参阅the official docs 了解更多详情和说明示例

    【讨论】:

      【解决方案2】:

      一般来说,How to stop insertion of Duplicate documents in a mongodb collection 有一个防止在 mongoDB 中添加重复文档的答案。

      这个想法是使用updateupsert=True 而不是insert_one。 因此,在插入 pymongo 的代码时会是

      db[collection_name].update(document,document,upsert=True)
      

      【讨论】:

      • 此命令显示错误 db[collection_name].update(document,document,upsert=True)
      【解决方案3】:

      这是你的文件

      doc = {"key":val}

      然后,使用 $set 更新您的文档

      update={"$set":doc} # 在更新中使用 $set 很重要

      db[collection_name].update(document, update, upsert=True)

      【讨论】: