mongoDB及mysql的去重语句

最近使用mongoDB用到数据去重,自己学习了一下,记录下结果。

1.mongoDB可视化工具:

 使用mongoDB的可视化工具robo 3T,选择需要去重的表,例如:

 去重语句如下:

//后的内容为注解,使用时删除

db.getCollection('soft_patent').aggregate(
    {
    $group:{
        '_id':'$id',
                    //'_id'作为标识,任意取,但是推荐和表字段对应,便于比较。
                    //'$id'代表需要去重的字段
        'uniqueIds':{'$addToSet': '$_id'},
                    //代表主键,后面重复词条就是根据唯一主键删除,
                    //uniqueIds是标识
        'count':{'$sum':1}
                    //按照$id进行group分组,获得相应的数量$sum
        }
    },
    {
        $match:{'count':{'$gt':1}}
                    //匹配count,数量>1的都要删除去重   
   }
    ).forEach(function(doc){
        //遍历
           doc.uniqueIds.shift();
           //根据主键删除
           db.getCollection('soft_patent').remove({_id:{$in:doc.uniqueIds}})
                //soft_patent表名
        })

 前半句也可用于判断是否有重复

db.getCollection('soft_patent').aggregate(
    {
    $group:{
        '_id':'$id',
                    
        'uniqueIds':{'$addToSet': '$_id'},
                    
        'count':{'$sum':1}
                    
        }
    },
    {
        $match:{'count':{'$gt':1}}
                    
   })

2.mysql去重:

比较简单,直接写语句

SELECT COUNT(*) FROM `codig_rel.soft_patent` GROUP BY id

DELETE
FROM
    `codig_rel.soft_patent`
WHERE
    id IN (
        (SELECT * FROM (SELECT
            id
        FROM
            `codig_rel.soft_patent`
        GROUP BY
            id
        HAVING
            COUNT(id) > 1) a)
    )

ps:在工作中,对于表数据的处理之前,一定要记得备份,避免重大损失。

发布了32 篇原创文章 · 获赞 11 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/chengsw1993/article/details/84639967
今日推荐