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

Spring Boot MongoRepository日期范围查询抛出JsonParseException且统计结果异常的问题排查与解决

Spring Boot MongoRepository日期范围查询抛出JsonParseException且统计结果异常的问题排查与解决

问题描述

我最近碰到一个MongoRepository日期统计的棘手问题:我的Mongo文档里createdOn字段存的是ISODate(对应Java的java.util.Date类型),当我通过REST客户端传入yyyy-MM-dd格式的from和to日期参数,调用自定义的统计方法时,不仅返回的统计数是0,还抛出了这样的异常:

org.bson.json.JsonParseException: JSON reader expected a string but found '?0'.

最开始我写的Repository查询代码是这样的:

public interface PaymentMongoLogDetailRepository extends MongoRepository<PaymentMongoLogDetail, String> {
    @Query(value = "{'$and' : [{'createdOn':{'$gt':ISODate(?0)}},{'createdOn':{'$lte':ISODate(?1)}},{'stripeResponse.sessionId':/cs_live/},{'stripeResponse.status':'success'}]}",count = true)
    Long findAllSuccessCounts(String from,String to);
}

但奇怪的是,把对应的查询语句直接放到Mongo Shell里执行,却能拿到正确的非零统计结果:

db.paymentMongoLogDetail.find({'$and' : [{'createdOn':{'$gt':ISODate('2025-01-24')}},{'createdOn':{'$lte':ISODate('2025-02-08')}},{'stripeResponse.sessionId':/cs_live/},{'stripeResponse.status':'success'}]}).count();

问题原因分析

折腾了一阵后,我发现问题出在两个地方:

  1. 占位符解析逻辑冲突:在@Query的JSON字符串里,我把占位符?0、?1嵌套在了ISODate()函数内部,Spring Data MongoDB的查询解析器没法识别这种写法——它会把ISODate(?0)当成一段不合法的JSON内容(?0不是有效的JSON字符串),直接抛出了解析异常。
  2. 参数类型不匹配:我用了String类型传日期,但Mongo里存的是ISODate类型,手动写ISODate()转换的方式在Repository注解里根本不生效,导致日期匹配完全失败,统计结果自然是0。

解决方法

经过调整,我修改后的代码终于正常工作了:

public interface PaymentMongoLogDetailRepository extends MongoRepository<PaymentMongoLogDetail, String> {
    @Query(value = "{'$and' : [{'createdOn':{'$gt': ?0,'$lte': ?1}},{'stripeResponse.sessionId':/cs_live/},{'stripeResponse.status':'success'}]}",count = true)
    Long findAllSuccessCounts(Date from,Date to);
}

这里的关键改动点:

  • 参数类型换成Date:直接用java.util.Date作为参数,Spring Data MongoDB会自动把它转换成Mongo支持的ISODate类型,完全不需要手动在查询语句里写ISODate()。
  • 合并日期条件:把createdOn的$gt和$lte条件合并到同一个对象里,既简化了查询语句,也避开了占位符嵌套的问题。
  • 移除ISODate()包裹:直接用?0和?1作为Date参数的占位符,查询解析器能正确识别并替换成对应的ISODate值,彻底解决了JSON解析异常的问题。

备注:内容来源于stack exchange,提问作者JPG

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 09:29:28