有两种方式:
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:"collection"}这样将你的收藏名称放入$out运算符中,但是没有回头路。
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"]}})