MongoRepository findByCreatedAtBetween 未返回准确结果

2024-03-14

我在 Mongo 中的文档结构是这样的:

db.user.find()

{
        "_id" : ObjectId("560fa46930a8e74be720009a"),
        "createdAt" : ISODate("2015-10-03T09:47:56.333Z"),
        "message" : "welcome",
}
{
            "_id" : ObjectId("560fa46930a8e723e720009a"),
            "createdAt" : ISODate("2015-10-03T09:48:25.048Z"),
            "message" : "thank you"
}

当我在 Mongo Shell 中使用以下查询来查找两个给定时间戳之间的文档时,我得到了正确的结果:

db.user.find({createdAt:{$gte:ISODate("2015-10-03T09:40:25.048Z"),$lte:ISODate("2015-10-03T09:50:56.333Z")}})

我在 REST 服务中使用 MongoRepository 和 Spring 来处理 Java 驱动程序。以下是用户存储库:

public interface UserRepository extends MongoRepository<User, String> 
{
       ArrayList<User> findbyCreatedAtBetween(Date d1, Date d2);

}

当我在我的服务中拨打以下电话时,它不会返回任何结果userRepository.findbyCreatedAtBetween(2015-10-03T09:40:25.048Z, 2015-10-03T09:50:29.006Z)

但是,当我将 d1 作为前一天给出时,它会返回结果: userRepository.findbyCreatedAtBetween(2015-10-02T09:40:25.048Z, 2015-10-03T09:50:29.006Z)

关于如何解决这个问题有什么想法吗?请帮忙!


分解一下,带有关键字的查询Between正在针对 MongoDB 数据库执行,并得出逻辑结果{"createdAt" : {"$gt" : d1, "$lt" : d2}}因此您有可能无法获得包含以下内容的文件createdAt给定日期范围内的日期,即d1 < createdAt < d2因为给定的日期范围不满足标准。以下是一些关于这个问题的解释,仅供参考查询方式 http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongodb.repositories.queries:

查询方法支持的关键字

Keyword     Sample                              Logical result
After       findByBirthdateAfter(Date date)     {"birthdate" : {"$gt" : date}}
Before      findByBirthdateBefore(Date date)    {"birthdate" : {"$lt" : date}}
Between     findByAgeBetween(int from, int to)  {"age" : {"$gt" : from, "$lt" : to}}

作为解决方法,您可能需要使用@Query http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongodb.repositories.queries.json-based注解。我还没有对此进行测试,但您可能想尝试以下自定义查询实现示例:

public interface UserRepository extends MongoRepository<User, String>  {
    @Query(value = "{ 'createdAt' : {$gte : ?0, $lte: ?1 }}")
    public ArrayList<User> findbyCreatedAtBetween(Date from, Date to);
}

如果上述方法不适合您,请创建自定义接口和实现类来执行自定义查询。例如,创建一个名称附加的接口Custom:

public interface UserRepositoryCustom {
    public List<User> findbyCreatedAtBetween(Date from, Date to); 
}

修改UserRepository并添加UserRepositoryCustom待扩展接口:

@Repository
public interface UserRepository extends UserRepositoryCustom, MongoRepository {

}

创建您的实现类来实现中定义的方法UserRepositoryCustom界面。

public class UserRepositoryImpl implements UserRepositoryCustom {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ArrayList<User> findbyCreatedAtBetween(Date from, Date to) {
        return mongoTemplate.find(
            Query.addCriteria(Criteria.where("createdAt").gte(from).lte(to));
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MongoRepository findByCreatedAtBetween 未返回准确结果 的相关文章

随机推荐