我有一个集合,其中对象的结构类似于
{'_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给我列出了不同的全文字段值,在这里我只想保存集合中具有唯一全文的对象。
答案 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聚合,在该聚合中,我们将记录按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"}
运算符中,但是没有回溯。
我们通过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"
]
}
}
}
}
}
])
data = list(collection.aggregate(...))
if len(data) > 0:
colleciton.remove({'_id':{'$in':data[0]["data"]}})