You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose聚合中$gt查询无结果,但find查询正常问题求助

问题排查与解决

核心原因

你代码里把dateLimit转成了ISO字符串(toISOString()),但MongoDB集合的createdAt字段是Date类型。Mongoose的find()方法会自动将字符串格式的日期参数转为Date对象做匹配,但在你使用的5.9.20版本中,aggregate()的$match阶段不会自动做这个类型转换,导致字符串和Date对象直接比较时不匹配,返回空数组。

解决方案

方案1:直接使用Date对象(推荐)

去掉toISOString()转换,保持dateLimit为Date类型:

const dateMonth = new Date();
dateMonth.setDate(dateMonth.getDate() - 10); // 最近10天
const dateLimit = new Date(dateMonth); // 保留Date类型

const resultScore = await ModelScoreUser.aggregate([{
  $match: {
    createdAt: {$gt: dateLimit}
  }
}]);

方案2:在$match中统一类型

如果必须用字符串格式日期,可通过MongoDB的$toDate操作符将字符串转为Date后再比较:

const dateMonth = new Date();
dateMonth.setDate(dateMonth.getDate() - 10);
const dateLimit = new Date(dateMonth).toISOString();

const resultScore = await ModelScoreUser.aggregate([{
  $match: {
    createdAt: {$gt: {$toDate: dateLimit}}
  }
}]);

补充说明

find()方法内部会自动处理日期字符串到Date对象的转换,所以能正常匹配数据;而旧版Mongoose的aggregate()对$match阶段的参数类型转换支持不完善,必须保证比较的类型一致(同为Date对象,或通过操作符统一类型)。

内容的提问来源于stack exchange,提问作者Ashko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 08:59:55