首页 / 数据库 / MySQL / MongoDB 分组查询统计去掉重复的记录
mongodb版本号是,MongoDB shell version: 2.4.4
操作环境,shell窗口 ,如下所示:[mongo_user@mongodb_dbs ~]# mongo --port 30100MongoDB shell version: 2.4.4connecting to: 127.0.0.1:30000/testmongos> mongos> use posswitched to db posmongos>
1,先统计分组记录数,以paymentOrder字段来分组统计,查询出所有的统计结果,分组统计数>1的
// 这里分组统计出来取分组字段paymentOrder的值_id、最大的objectid值max_id、分组统计数countvar group=([ {$group:{_id:"$paymentOrder", max_id: {$max:"$_id"},count: { $sum: 1 }}}, {$sort:{count:-1}}])
2,定义就是找出存在重复的分组,使用管道操作符 match,条件是普通查询的格式,但是作用于[Math Processing Error] group的输出结果的格式:
var match ={"$match":{"count" : {"$gt" : 2}}};
3,最后,通过聚合框架函数db.paymentinfo.aggregate(group, match)就得到了存在重复数据的分组。这个过程看似复杂,其实实现的只是T-SQL中的group by … having … 的语法。
var ds=db.paymentinfo.aggregate(group, match);PS:这里match无效,出来很多count为1的数据,也就是说{“match":{"count" : {"[Math Processing Error] gt” : 2}}};失败,why?
4,删除之前先备份好
备份/usr/local/mongodb/mongodb-linux-x86_64-2.4.4/bin/mongoexport --port 30000 -d pos -c paymentinfo-o /home/backup/mongodb_pos_paymentinfo_3.txt5,开始循环删除
这里ds就是一个大的结果集,直接用ds.result就可以获取结果集里面分组查询出来的数据://下面开始启用循环来遍历,aggregate出来的result已经具备了数组的特性,可以直接for循环处理var ds = db.paymentinfo.aggregate(group, match);for (var i = 0;i <ds.result.length ; i++) {var child=ds.result[i];var count=child.count;//因为上面第二步的{"$match":{"count" : {"$gt" : 2}}};过滤无效,所以这里加一个count>1来过滤掉没有重复的数据,只对有重复的进行数据处理操作if(count>1){ var oid=child.max_id;print(count);//这里获取分组中最大的objectid的集合记录的objectidvar payorder=child._id;//获取重复的paymentOrder的所有记录查???出来,进行遍历var ps=db.paymentinfo.find({"paymentOrder":payorder });//直接find后需要用toArray()来进行处理变成数组这样才可以遍历var psc=ps.toArray();for(var j=0; j<psc.length; j++){var pchild=psc[j];//将objectid进行遍历,如果是最大的那条记录保留,不是就删除remove掉if(oid.toString()==pchild._id.toString()){print("the same one");print(pchild._id.toString());print(oid.toString());}else{print("the other one -----");print(pchild._id.toString());print(oid.toString());db.paymentinfo.remove({"_id":pchild._id});}}}}BY THE WAY:如果你copy我的脚本,去shell下的mongos客户端执行报错,有可能是格式错误,你可以去掉所有的换行符号或者你自己手动输入一遍,去执行,就不会报错了。更多MongoDB相关教程见以下内容:CentOS 编译安装 MongoDB与mongoDB的php扩展 http://www.linuxidc.com/Linux/2012-02/53833.htmCentOS 6 使用 yum 安装MongoDB及服务器端配置 http://www.linuxidc.com/Linux/2012-08/68196.htmUbuntu 13.04下安装MongoDB2.4.3 http://www.linuxidc.com/Linux/2013-05/84227.htmMongoDB入门必读(概念与实战并重) http://www.linuxidc.com/Linux/2013-07/87105.htmUbunu 14.04下MongoDB的安装指南 http://www.linuxidc.com/Linux/2014-08/105364.htm《MongoDB 权威指南》(MongoDB: The Definitive Guide)英文文字版[PDF] http://www.linuxidc.com/Linux/2012-07/66735.htmNagios监控MongoDB分片集群服务实战 http://www.linuxidc.com/Linux/2014-10/107826.htm基于CentOS 6.5操作系统搭建MongoDB服务 http://www.linuxidc.com/Linux/2014-11/108900.htmMongoDB 的详细介绍:请点这里
MongoDB 的下载地址:请点这里本文永久更新链接地址