【发布时间】:2025-12-05 17:35:01
【问题描述】:
我正在使用 pymongo "insert_one", 我想防止插入两个具有相同“名称”属性的文档。
- 我一般如何防止重复?
- 如何为名称等特定属性配置它?
谢谢!
我的代码:
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
【问题讨论】: