MongoDB中如何比较日期值并进行分组聚合?
按日期分组并检查日期相等性的解决方案
嘿,我来帮你搞定这个日期分组的需求!针对你给出的JSON数据,我用JavaScript写了个直观的实现方案,这也是处理这类数据分组最常用的方式之一。
首先先把你的原始数据放出来方便参考:
const data = [ {"creationDate": "2021/3/19", "_id": "60549366ab4eb00aa1ed2fd9", "avgPower": 8241, "WaterConsumption": 22}, {"creationDate": "2021/3/19", "_id": "605493f4ab4eb00aa1ed2fda", "avgPower": 8241, "WaterConsumption": 22}, {"creationDate": "2021/2/17", "_id": "60549433ab4eb00aa1ed2fdb", "avgPower": 4300, "WaterConsumption": 32} ];
基础分组实现
用Array.reduce()方法就能轻松实现按日期分组,核心逻辑是用creationDate作为键,把同一天的数据归到同一个数组里:
const groupedByDate = data.reduce((acc, item) => { // 提取当前项的日期作为分组键 const dateKey = item.creationDate; // 如果累加器里还没有这个日期的分组,就初始化一个空数组 if (!acc[dateKey]) { acc[dateKey] = []; } // 把当前项加入对应日期的分组 acc[dateKey].push(item); return acc; }, {}); console.log(groupedByDate);
运行这段代码后,你会得到这样的分组结果:
{ "2021/3/19": [ {"creationDate": "2021/3/19", "_id": "60549366ab4eb00aa1ed2fd9", "avgPower": 8241, "WaterConsumption": 22}, {"creationDate": "2021/3/19", "_id": "605493f4ab4eb00aa1ed2fda", "avgPower": 8241, "WaterConsumption": 22} ], "2021/2/17": [ {"creationDate": "2021/2/17", "_id": "60549433ab4eb00aa1ed2fdb", "avgPower": 4300, "WaterConsumption": 32} ] }
进阶:数值聚合(求和/平均值)
如果你的需求不只是单纯分组,还要对同一天的avgPower和WaterConsumption做计算(比如求和或取平均),可以修改reduce的逻辑:
const aggregatedByDate = data.reduce((acc, item) => { const dateKey = item.creationDate; if (!acc[dateKey]) { acc[dateKey] = { creationDate: dateKey, totalAvgPower: 0, totalWaterConsumption: 0, count: 0 }; } // 累加数值 acc[dateKey].totalAvgPower += item.avgPower; acc[dateKey].totalWaterConsumption += item.WaterConsumption; acc[dateKey].count += 1; // 可选:计算平均值 acc[dateKey].averageAvgPower = acc[dateKey].totalAvgPower / acc[dateKey].count; acc[dateKey].averageWaterConsumption = acc[dateKey].totalWaterConsumption / acc[dateKey].count; return acc; }, {}); // 把对象转成数组(可选,方便后续遍历) const aggregatedArray = Object.values(aggregatedByDate); console.log(aggregatedArray);
这样输出的就是每个日期的聚合结果,比如2021/3/19的总avgPower是16482、总用水量是44,平均值和单条数据一致,完全匹配你的数据情况。
内容的提问来源于stack exchange,提问作者Gabriel Savian
相关产品推荐
相关产品推荐

