重要提示:从 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 } )
这是一个会话的跟踪,它显示了在使用 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 }
>