MongoDB 聚合分组取第一条的案例及实现

关键字:MongoDB; aggregate;forEach

今天开发同学向我们提了一个紧急的需求,从集合mt_resources_access_log中,根据字段refererDomain分组,取分组中最近一笔插入的数据,然后将这些符合条件的数据导入到集合mt_resources_access_log_new中。

接到这个需求,还是有些心虚的,原因有二,一是,业务需要,时间紧;二是,实现这个功能MongoDB聚合感觉有些复杂,聚合要走好多步。

数据记录格式如下:

记录1 { "_id" : ObjectId("5c1e23eaa66bf62c0c390afb"), "_class" : "C1", "resourceUrl" : "/static/js/p.js", "refererDomain" : "1234", "resourceType" : "static_resource", "ip" : "17.17.13.13", "createTime" : ISODate("2018-12-22T19:45:46.015+08:00"), "disabled" : 0 } 记录2 { "_id" : ObjectId("5c1e23eaa66bf62c0c390afb"), "_class" : "C1", "resourceUrl" : "/static/js/p.js", "refererDomain" : "1234", "resourceType" : "Dome_resource", "ip" : "17.17.13.14", "createTime" : ISODate("2018-12-21T19:45:46.015+08:00"), "disabled" : 0 } 记录3 { "_id" : ObjectId("5c1e23eaa66bf62c0c390afb"), "_class" : "C2", "resourceUrl" : "/static/js/p.js", "refererDomain" : "1235", "resourceType" : "static_resource", "ip" : "17.17.13.13", "createTime" : ISODate("2018-12-20T19:45:46.015+08:00"), "disabled" : 0 }

记录4 { "_id" : ObjectId("5c1e23eaa66bf62c0c390afb"), "_class" : "C2", "resourceUrl" : "/static/js/p.js", "refererDomain" : "1235", "resourceType" : "Dome_resource", "ip" : "17.17.13.13", "createTime" : ISODate("2018-12-20T19:45:46.015+08:00"), "disabled" : 0 }  

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyzzdg.html