Skip to main content
 首页 » 编程设计

python之实现 ensureIndex() 以使用 pymongo 删除重复文档

2025年05月04日17unruledboy

我需要删除基于字段“X”的唯一值的重复条目。它在 mongodb shell 中工作正常:

db.collection.ensureIndex({x' : 1},{unique: true, dropDups: true}) 

我想使用 pymongo 运行它,我使用的代码如下:

import pymongo 
import mmh3 
 
conn = pymongo.MongoClient() 
db = conn['scrapy-mongodb'] 
 
db.collection.ensure_index({'x' : 1}, {'$unique' : True, '$dropDups' : True}) 

这段代码抛出:

TypeError: if no direction is specified, key_or_list must be an instance of list

我哪里出错了?

请您参考如下方法:

您在几个方面的 pymongo 调用语法错误。假设“collection”是集合的名称,这应该可以工作。

db.collection.ensure_index([("x" , pymongo.ASCENDING), ("unique" , True), ("dropDups" , True)]) 

Pymongo(和 Python)需要一个键方向对列表而不是字典,因为字典是无序的。升序索引的语法也是 pymongo.ASCENDING。 unique 和 dropDups 终于不需要“$”了。