在MongoDB中删除重复项 [英] Remove duplicate in MongoDB

查看:88
本文介绍了在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆