python - 检查并删除 python MongoDB 中的重复项

标签 python mongodb

我想从 MongoDB 中的集合中删除重复数据。我怎样才能做到这一点?

请引用此示例来了解我的问题:

我的收藏名称和问题位于此列/行中,如下 -

{
"questionText" : "what is android ?",
"__v" : 0,
"_id" : ObjectId("540f346c3e7fc1234ffa7085"),
"userId" : "102"
},

{
"questionText" : "what is android ?",
"__v" : 0,
"_id" : ObjectId("540f346c3e7fc1054ffa7086"),
"userId" : "102"
}

如何删除同一用户 ID 的重复问题?有什么帮助吗?

我正在使用 Python 和 MongoDB。

最佳答案

重要:从 MongoDB 3.x 开始删除了 dropDups 选项,因此此解决方案仅对 MongoDB 2.x 及之前版本有效。 dropDups 选项没有直接替代选项。问题的答案http://stackoverflow.com/questions/30187688/mongo-3-duplicates-on-unique-index-dropdups提供一些可能的替代方法来删除 Mongo 3.x 中的重复项。

通过在集合上创建唯一索引并指定 dropDups 选项,可以从 MongoDB 集合中删除重复记录。

假设集合包含一个名为 record_id 的字段,该字段唯一标识集合中的记录,则用于创建唯一索引并删除重复项的命令是:

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

这是一个 session 的跟踪,显示了使用 dropDups 创建唯一索引之前和之后集合的内容。请注意,创建索引后不再存在重复记录。

> db.pages.find()
{ “_id” : ObjectId(“52829c886602e2c8428d1d8c”), “leaf_num” : “1”, “scan_id” : “smithsoniancont251985smit”, “height” : 3464, “width” : 2548 }
{ “_id” : ObjectId(“52829c886602e2c8428d1d8d”), “leaf_num” : “1”, “scan_id” : “smithsoniancont251985smit”, “height” : 3464, “width” : 2548 }
{ “_id” : ObjectId(“52829c886602e2c8428d1d8e”), “leaf_num” : “2”, “scan_id” : “smithsoniancont251985smit”, “height” : 3587, “width” : 2503 }
{ “_id” : ObjectId(“52829c886602e2c8428d1d8f”), “leaf_num” : “2”, “scan_id” : “smithsoniancont251985smit”, “height” : 3587, “width” : 2503 }
>
> db.pages.ensureIndex( { scan_id:1, leaf_num:1 }, { unique:true, dropDups:true } )
>
> db.pages.find()
{ “_id” : ObjectId(“52829c886602e2c8428d1d8c”), “leaf_num” : “1”, “scan_id” : “smithsoniancont251985smit”, “height” : 3464, “width” : 2548 }
{ “_id” : ObjectId(“52829c886602e2c8428d1d8e”), “leaf_num” : “2”, “scan_id” : “smithsoniancont251985smit”, “height” : 3587, “width” : 2503 }
>

关于python - 检查并删除 python MongoDB 中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51240581/

相关文章:

php - 问题持久化嵌套的嵌套嵌入文档

python - 在Python中使用groupby划分两个数据框

python - GAE 中的多对多关系。查询失败

python - 将 pytest 作为预提交钩子(Hook)运行//没有这样的文件或目录问题

javascript - 如何让此 DELETE 路由在我的 products.js 路由中工作?

mongodb - Mongoose:在数组中查找标签并返回匹配的文档

python - Pandas 本地化和转换日期时间列而不是日期时间索引

python - 如何获得flask_sqlalchemy 类的PEP 484 类型提示?

mongodb - 内部结构地理空间索引

mongodb - mgo 有序排序聚合