一个mongo聚合数据的例子
2023-03-14 10:24:32 时间
mongo里每天会记录一些这样的数据,要把这些数据按照时间聚合。
function statisticsSchoolForTimes(nowtime) { db.getCollection('all').aggregate( [ {$match:{"time":nowtime}}, { $group:{ _id:{"schoolId":"$schoolId","userRole":"$userRole"}, provinceCode:{$first:"$provinceCode"}, provinceValue:{$first:"$provinceValue"}, cityValue:{$first:"$cityValue"}, cityCode:{$first:"$cityCode"}, countyCode:{$first:"$countyCode"}, countyValue:{$first:"$countyValue"}, schoolLevel:{$first:"$schoolLevel"}, schoolName:{$first:"$schoolName"}, schoolId:{$first:"$schoolId"}, time:{$first:"$time"}, userRole:{$first:"$userRole"} } } ]).forEach(function(x){ var praiseNum=db.getCollection('all').find({"schoolId":x.schoolId,"time":x.time,"type":"praise","userRole":x.userRole}).count(); var downloadNum=db.getCollection('all').find({"schoolId":x.schoolId,"time":x.time,"type":"download","userRole":x.userRole}).count(); var collectionNum=db.getCollection('all').find({"schoolId":x.schoolId,"time":x.time,"type": "collection","userRole":x.userRole}).count(); var commentNum=db.getCollection('all').find({"schoolId":x.schoolId,"time":x.time,"type":"comment","userRole":x.userRole}).count(); var browseNum=db.getCollection('all').find({"schoolId":x.schoolId,"time":x.time,"type":"browse","userRole":x.userRole}).count(); db.getCollection('school').insert(x); db.getCollection('school').update({"schoolId":x.schoolId,"time":x.time,"userRole":x.userRole},{'$set': {'praiseNum': praiseNum,'downloadNum': downloadNum,'collectionNum': collectionNum,'commentNum': commentNum,'browseNum': browseNum}}); }) }
java里面每天凌晨定时执行这个函数即可
private static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public void run() { try { System.out.println("开始数据统计聚合任务,时间为:"+formatter.format(Calendar.getInstance().getTime())); aggregate(); System.out.println("结束数据统计聚合任务,时间为:"+formatter.format(Calendar.getInstance().getTime())); } catch (Exception e) { System.out.println("-------------数据统计聚合任务发生异常--------------"+e.toString()); } }
public static void aggregate(){ System.out.println("开始数据统计聚合任务,时间为:"+formatter.format(Calendar.getInstance().getTime())); MongoUtils mu = new MongoUtils(); MongoUtils.createMongoClient(); DB db=mu.getDB(MongoUtils.DATABASE); String nowTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); db.eval("statisticsDistrictForTimes('"+nowTime+"')"); db.eval("statisticsSchoolForTimes('"+nowTime+"')"); mu.closeConnection(); System.out.println("结束数据统计聚合任务,时间为:"+formatter.format(Calendar.getInstance().getTime())); }
聚合之后的数据是这样的:
相关文章
- 数据孤岛是业务效率的无声杀手
- 2023展望:新的一年将给大数据分析领域带来什么?
- 阿里云ADB基于Hudi构建Lakehouse的实践
- 大数据在医疗保健领域的使用案例
- 微软增加说明:KB5021751 更新扫描已经 / 即将过时 Office 过程中不会触碰用户隐私
- 2022 Gartner全球云数据库管理系统魔力象限发布 腾讯云数据库入选
- 场景化、重实操,分享一个实时数仓实践案例
- Arctic的湖仓一体践行之路
- 分布式计算MapReduce究竟是怎么一回事?
- 淘系数据模型治理优秀实践
- 大数据分析对医疗保健的影响
- 当我们说大数据Hadoop,究竟在说什么?
- 2022年及以后大数据的五个发展趋势
- 网易严选离线数仓治理实践
- 2023 年数据治理趋势
- 一份“靠谱”的年度经营计划,你学会了吗?
- 漫谈对大数据的思考
- 测试一下,读懂数据的能力,你有吗?
- 用艺术的眼光探索数据之美
- 聊聊数据分析成果如何落地