如何在MongoDB Compass中按年份统计createdAt字段的数据量?
MongoDB按createdAt年份统计数据量的实现方法
核心思路
利用MongoDB聚合管道,通过$project提取年份字段,再结合$group完成分组统计。你的createdAt是标准ISODate格式,可直接用日期操作符处理。
基础查询(统计所有年份的数据量)
db.collection.aggregate([ // 提取createdAt中的年份,生成新字段year { $project: { year: { $year: "$createdAt" }, _id: 0 // 可选,不需要返回原_id可设为0 } }, // 按year分组,统计每组文档数量 { $group: { _id: "$year", count: { $sum: 1 } } }, // 可选:按年份升序排序,优化结果可读性 { $sort: { _id: 1 } } ])
只统计指定年份(如2021和2022年)
如果仅需要特定年份的数据,可在聚合开头添加$match阶段筛选时间范围:
db.collection.aggregate([ // 先筛选2021-2022年的数据 { $match: { createdAt: { $gte: ISODate("2021-01-01T00:00:00Z"), $lt: ISODate("2023-01-01T00:00:00Z") } } }, // 提取年份 { $project: { year: { $year: "$createdAt" }, _id: 0 } }, // 分组统计 { $group: { _id: "$year", count: { $sum: 1 } } } ])
特殊情况:createdAt为字符串类型
如果createdAt实际是字符串而非ISODate,需先用$toDate转换格式后再提取年份:
db.collection.aggregate([ { $project: { year: { $year: { $toDate: "$createdAt" } }, _id: 0 } }, { $group: { _id: "$year", count: { $sum: 1 } } } ])
内容的提问来源于stack exchange,提问作者ASHafizullah
相关产品推荐
相关产品推荐

