有没有一种方法可以消除集合中的所有重复项?

时间:2020-03-11 17:46:02

标签: python python-3.x mongodb mongodb-query pymongo

我有一个集合,其中对象的结构类似于

{'_id': ObjectId('5e691cb9e73282f624362221'), 
 'created_at': 'Tue Mar 10 09:23:54 +0000 2020', 
 'id': 1237308186757120001, 
 'id_str': '1237308186757120001', 
 'full_text': 'See you in July'}

我正在努力只保留具有唯一全文的对象。使用distinct only给我列出了不同的全文字段值,在这里我只想保存集合中具有唯一全文的对象。

2 个答案:

答案 0 :(得分:0)

有,代码应如下所示:

dict = {"a": 1, "b": 2, "c": 3, "a": 5, "d": 4, "e": 5, "c": 8}

#New clean dictionary
unique = {}
#Go through the original dictionary's items
for key, value in dict.items():
    if(key in unique.keys()):
    #If the key already exists in the new dictionary
        continue
    else:
    #Otherwise
        unique[key] = value

print(unique)

希望对您有帮助!

答案 1 :(得分:0)

有2种方法:

MongoDB方式

我们执行MongoDB聚合,在该聚合中,我们将记录按full_text分组,仅过滤唯一的文档并将其插入到集合中。 (在外壳中)

db.collection.aggregate([
  {
    $group: {
      _id: "$full_text",
      data: {
        $push: "$$ROOT"
      },
      count: {
        $sum: 1
      }
    }
  },
  {
    $match: {
      count: {
        $eq: 1
      }
    }
  },
  {
    $addFields: {
      data: {
        $arrayElemAt: [
          "$data",
          0
        ]
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: "$data"
    }
  },
  {
    $out: "tmp"
  }
])

运行此查询时,它将创建具有唯一full_text值的新集合。您可以删除旧收藏并将其重命名。

您也可以像$out这样将集合名称放入{$out:"collection"}运算符中,但是没有回溯

Python方式

我们通过full_text字段对MongoDB进行聚合分组,过滤重复的文档,并创建一个包含所有_id要删除的单个数组。 MongoDB返回结果后,我们将对重复的文档执行remove命令。

db.collection.aggregate([
  {
    $group: {
      _id: "$full_text",
      data: {
        $push: "$_id"
      },
      count: {
        $sum: 1
      }
    }
  },
  {
    $match: {
      count: {
        $gt: 1
      }
    }
  },
  {
    $group: {
      _id: null,
      data: {
        $push: "$data"
      }
    }
  },
  {
    $addFields: {
      data: {
        $reduce: {
          input: "$data",
          initialValue: [],
          in: {
            $concatArrays: [
              "$$value",
              "$$this"
            ]
          }
        }
      }
    }
  }
])

MongoPlayground

伪代码

data = list(collection.aggregate(...))
if len(data) > 0:
    colleciton.remove({'_id':{'$in':data[0]["data"]}})