1、MongoDB查询重复数据
db.Wuyou_Data.aggregate([
{
$group:{_id:{position_name:'$position_name',company_name:'$company_name',work_location:'$work_location',basic_salary:'$basic_salary',publish_time:'$publish_time',education_required:'$education_required',work_experience:'$work_experience',company_nature:'$company_nature',company_scale:'$company_scale',details_link:'$details_link',industry_category:'$industry_category',career_category:'$career_category'},count:{$sum:1}}
},{$match:{count:{$gt:1}}}],{allowDiskUse:true})
2、MongoDB去重
db.Wuyou_Data.aggregate([
{
$group:{_id:{position_name:'$position_name',company_name:'$company_name',work_location:'$work_location',basic_salary:'$basic_salary',publish_time:'$publish_time',education_required:'$education_required',work_experience:'$work_experience',company_nature:'$company_nature',company_scale:'$company_scale',details_link:'$details_link',industry_category:'$industry_category',career_category:'$career_category',career_link:'$career_link',industry_link:'$industry_link'},count:{$sum:1},dups:{$addToSet:'$_id'}}
},
{
$match:{count:{$gt:1}}
}
],{
allowDiskUse:true
}).forEach(function(doc){
doc.dups.shift();
db.Wuyou_Data.remove({_id:{$in:doc.dups}});
})
解析:
(1)根据position_name、company_name等分组并统计数量,$group只会返回参与分组的字段,使用$addToSet在返回结果数组中增加_id字段
(2)使用$match匹配数量大于1的数据
(3)doc.dups.shift();表示从数组第一个值开始删除;作用是剔除重复数据其中一个_id,让后面的删除语句不会删除所有数据
(4)使用forEach循环根据_id删除数据
(5)$addToSet 操作符只有在值没有存在于数组中时才会向数组中添加一个值。如果值已经存在于数组中,$addToSet返回,不会修改数组。
(6)allowDiskUse: true 数据过大会报内存错误:Exceeded memory limit for $group, but didn't allow external sort. Pass allowDiskUse:true to opt in 可以在后面添加上这个属性就不会了。数据不大的情况下,可以不用试一下
注意:forEach和$addToSet的驼峰写法不能全部写成小写,因为mongodb严格区分大小写。