如何在MongoDB中筛选近6个月及近30天的指定状态用户数据?
MongoDB 筛选近30天/近6个月用户数据
在已有status: '1'筛选条件的基础上,添加日期范围过滤可通过MongoDB的$gte运算符结合日期计算实现,以下是具体方案:
1. 筛选近30天的数据
直接计算当前时间往前推30天的时间戳,用$gte匹配createdAt大于等于该时间的文档:
// 计算30天前的日期 const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000); // 执行查询(替换yourCollectionName为实际集合名) db.yourCollectionName.find({ status: '1', createdAt: { $gte: thirtyDaysAgo } }).toArray();
说明:Date.now()获取当前毫秒级时间戳,减去30天对应的毫秒数(30天×24小时×60分钟×60秒×1000毫秒)得到30天前的日期对象,$gte确保只返回该时间点之后创建的数据。
2. 筛选近6个月的数据
使用Date对象的setMonth方法计算6个月前的日期(自动处理跨年份、不同月份天数差异的问题):
// 计算6个月前的日期 const sixMonthsAgo = new Date(); sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6); // 执行查询(替换yourCollectionName为实际集合名) db.yourCollectionName.find({ status: '1', createdAt: { $gte: sixMonthsAgo } }).toArray();
说明:setMonth会自动调整年份,比如当前是2023年1月,减6个月后会得到2022年7月的日期,比手动计算天数更准确。
聚合管道版本(可选)
如果需要结合其他聚合操作,可在$match阶段加入日期筛选:
// 近6个月数据的聚合查询(替换yourCollectionName为实际集合名) db.yourCollectionName.aggregate([ { $match: { status: '1', createdAt: { $gte: new Date(new Date().setMonth(new Date().getMonth() - 6)) } } } // 后续可添加其他聚合阶段(如$project、$group等) ]).toArray();
示例数据匹配结果:假设当前日期为2023年1月,近6个月的查询会返回createdAt为2022-11-14、2022-12-28、2023-01-02的文档,排除2021-11-28的旧数据。
内容的提问来源于stack exchange,提问作者Ankit Kumar
相关产品推荐
相关产品推荐

