MongoDB查询表中多字段字段组合重复数据并删除重复数据

参考:https://blog.csdn.net/liu911025/article/details/80882270
https://blog.csdn.net/qq_23375733/article/details/83147854

mongodb(js)美化:https://beautifier.io/

1.查询表中相同字段
根据title和currentDay组合查询,匹配数量大于1的数据

db.getCollection('biddings').aggregate([{
        '$group': {
            '_id': {
            'title': '$title',
            'currentDay': '$currentDay'
            },
            'uniqueIds': {
                '$addToSet': '$_id'
            },
            'count': {
                '$sum': 1
            }
        }
    },
    {
        '$match': {
            'count': {
                '$gt': 1
            }
        }
    }
], {
    allowDiskUse: true
})

2.删除表中相同数据
查询和删除语句,删除语句后面添加forEach循环

db.getCollection('biddings').aggregate([{
        '$group': {
            '_id': {
            'title': '$title',
            'currentDay': '$currentDay'
            },
            'uniqueIds': {
                '$addToSet': '$_id'
            },
            'count': {
                '$sum': 1
            }
        }
    },
    {
        '$match': {
            'count': {
                '$gt': 1
            }
        }
    }
], {
    allowDiskUse: true
}).forEach(function(doc) {
    doc.uniqueIds.shift();
    db.getCollection('biddings').remove({
        _id: {
            $in: doc.uniqueIds
        }
    });
})

解释:

1.根据bqyId分组并统计数量, $group只会返回参与分组的字段,使用$addToSet在返回结果数组中增加_id字段
2.使用$match匹配数量大于1的数据
3.doc.uniqueIds.shift();表示从数组第一个值开始删除;作用是踢除重复数据其中一个_id,让后面的删除语句不会删除所有数据
4.使用forEach循环根据_id删除数据
 $addToSet 操作符只有在值没有存在于数组中时才会向数组中添加一个值。如果值已经存在于数组中,$addToSet返回,不会修改数组。
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值