插入到具有 Python 唯一键的 MongoDB 集合

Insert to MongoDB collection that has unique key with Python

我有一个名为 englishWords 的集合,唯一索引是 "word" 字段。 当我这样做时

from pymongo import MongoClient

tasovshik = MongoClient()
db = tasovshik.tongler
coll = db.englishWords

f = open('book.txt')
for word in f.read().split():
    coll.insert( { "word": word } } )

我收到此错误消息

pymongo.errors.DuplicateKeyError: E11000 duplicate key error index: tongler.englishWords.$word_1 dup key: { : "Harry" }
,但当要插入第一个现有单词时它会停止插入。

我不想执行存在性检查,我想毫无问题地使用唯一索引的好处。

您可以执行以下操作:

for word in f.read().split():
    try:
        coll.insert( { "word": word } } )
    except pymongo.errors.DuplicateKeyError:
        continue

这将忽略错误。

还有,你在尝试之前是否放下了 collection?

我刚刚 运行 你的代码,一切看起来都不错,只是你在最后一行有一个额外的 }。删除它,你就没有 drop any 集合。每个 insert,都会创建自己的一批数据,因此无需删除之前的集合。

嗯,错误信息表明密钥 Harry 已经插入,您正在尝试使用相同的密钥再次插入。在您的整个代码中不是这样吗?

为避免不必要的异常处理,您可以执行更新插入:

from pymongo import MongoClient

tasovshik = MongoClient()
db = tasovshik.tongler
coll = db.englishWords

for word in f.read().split():
    coll.replace_one({'word': word}, {'word': word}, True)

最后一个参数指定 MongoDB 如果该值不存在则应插入该值。

这里是the documentation


编辑:为了更快地处理一长串单词,您可以像这样批量执行:

from pymongo import MongoClient

tasovshik = MongoClient()
db = tasovshik.tongler
coll = db.englishWords

bulkop = coll.initialize_unordered_bulk_op()
for word in f.read().split():
    bulkop.find({'word':word}).upsert()

bulkop.execute()

取自bulk operations documentation