我想从 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/