Skip to main content
 首页 » 编程设计

python之如何防止pymongo中的重复项

2025年05月04日12lyhabc

我正在使用 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

请您参考如下方法:

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

想法是使用 update 和 upsert=True 而不是 insert_one。 因此,在插入 pymongo 代码时将是

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