【问题标题】:Check and remove duplicates in python MongoDB在 python MongoDB 中检查和删除重复项
【发布时间】:2018-07-09 07:57:01
【问题描述】:

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

请参考这个例子来理解我的问题:

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

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

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

如何删除同一个 userId 的重复问题?有什么帮助吗?

我正在使用 Python 和 MongoDB。

【问题讨论】:

    标签: python mongodb


    【解决方案1】:

    重要提示:从 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 }
    >
    

    【讨论】:

      【解决方案2】:

      现在 dropOps 已被弃用。你可以使用熊猫。

      1. 从 mongodb 中选择你需要的字段
      2. 使用 pandas.DataFrame.duplicated 将所有重复项标记为 True,但第一个除外
      3. 使用它们的_id在集合中删除它们(标记为重复的)

      【讨论】:

        猜你喜欢
        • 2015-04-23
        • 2015-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多