本文共 2034 字,大约阅读时间需要 6 分钟。
MongoDB中有一个名为stat_list的集合,存储了每天的统计数据。为了按月统计数据,我们需要使用MongoDB的聚合函数aggregate。
当前的daily_count字段存储的是带有单位的字符串,例如“164.34万”。为了避免数据处理问题,我们需要将其去掉单位后转换为整数。可以使用正则表达式提取数字部分:
friendsCount = item.daily_count.match(/.*?(?=万)/);newFriendsCount = parseFloat(friendsCount[0]);
更新后的daily_count将从“164.34万”变为“164.34”。
date字段的值通常格式为“YYYY-MM-DD”,例如“2019-06-12”。我们可以使用substr函数提取月份:
month = substr(date, 0, 7); // 提取前7个字符,例如“2019-06”中的“06”
在MongoDB中,使用aggregate函数可以对数据进行批量操作。以下是一个示例:
db.getCollection('stat_list_copy').aggregate([ { $project: { date: { $regexMatch: { path: '$date', template: new Date().toISOString().split('T')[0] } }, month: { $substr: { path: '$date', offset: 0, length: 2 } }, daily_count: { $toInteger: { $cond: { if: { $type: 'string', $eq: ['$', '万'] }, then: '$daily_count', else: 0 } } } } }, { $group: { _id: '$month', total: { $sum: '$daily_count' } } }]) 在处理过程中,可以选择逐个更新数据:
db.getCollection('stat_list_copy').find().forEach(function(item) { friendsCount = item.daily_count; friendsCount = (friendsCount.match(/.*?(?=万)/)); newFriendsCount = parseFloat(friendsCount[0]); db.getCollection('stat_list_copy').update({'_id': item._id}, { $set: { 'daily_count': newFriendsCount } });}); 通过以上步骤,可以实现按月统计的需求。记得在实际应用中根据需要调整正则表达式和处理逻辑,以适应不同的数据格式和业务需求。
转载地址:http://djffk.baihongyu.com/