删除 MongoDB 中的重复项 [英] Remove duplicate in MongoDB
问题描述
我有一个名为contact_id"的字段的集合.在我的收藏中,我有使用此密钥的重复寄存器.
I have a collection with the field called "contact_id". In my collection I have duplicate registers with this key.
如何删除重复项,导致只有一个寄存器?
How can I remove duplicates, resulting in just one register?
我已经试过了:
db.PersonDuplicate.ensureIndex({"contact_id": 1}, {unique: true, dropDups: true})
但是没有用,因为函数 dropDups
在 MongoDB 3.x 中不再可用
But did not work, because the function dropDups
is no longer available in MongoDB 3.x
我使用的是 3.2
推荐答案
是的,dropDups 已经一去不复返了.但是你绝对可以通过一点点努力来实现你的目标.
Yes, dropDups is gone for good. But you can definitely achieve your goal with little bit effort.
您需要先找到所有重复的行,然后删除除第一个之外的所有行.
You need to first find all duplicate rows and then remove all except first.
db.dups.aggregate([{$group:{_id:"$contact_id", dups:{$push:"$_id"}, count: {$sum: 1}}},
{$match:{count: {$gt: 1}}}
]).forEach(function(doc){
doc.dups.shift();
db.dups.remove({_id : {$in: doc.dups}});
});
如您所见,doc.dups.shift()
将首先从数组中删除 _id,然后删除 dups 数组中包含剩余 _id 的所有文档.
As you see doc.dups.shift()
will remove first _id from array and then remove all documents with remaining _ids in dups array.
上面的脚本将删除所有重复的文档.
script above will remove all duplicate documents.
这篇关于删除 MongoDB 中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!