简体   繁体   English

如何使用考虑两个字符串日期范围的标准在 Mongo DB 中构建 Spring Query

[英]How to build a Spring Query in Mongo DB with a criteria considering two string date range

I have to build a criteria of a find query using a date field which is stored in String format.我必须使用以字符串格式存储的日期字段来构建查找查询的条件。 The criteria I've written is like this:我写的标准是这样的:

Query findQuery = new Query()
findQuery.addCriteria(Criteria.where(mongoField).gt(startDate).lt(endDate));

where the "mongofield" is a String type, but "startDate" and "endDate" are a LocalDate type.其中“mongofield”是 String 类型,但“startDate”和“endDate”是 LocalDate 类型。

This criteria obviously doesn't work because the comparison is ineffective.这个标准显然不起作用,因为比较无效。 I've found that I should use $expr operator together with $dateFromString, but I didn't find any clear example of use in Java code.我发现我应该将 $expr 运算符与 $dateFromString 一起使用,但我没有在 Java 代码中找到任何明确的使用示例。

Please, can anyone help me in writing a good statement in Spring Java code?拜托,任何人都可以帮助我在 Spring Java 代码中写出一个好的声明吗?

You can convert LocalDate to a string and then compare您可以将 LocalDate 转换为字符串,然后进行比较

        LocalDate startDate = LocalDate.now();
        LocalDate endDate = LocalDate.now().plusDays(20);
        // Define time format converter
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        // Convert LocalDate type to String type
        Criteria criteria = Criteria.where("mongoField").is("").gte(startDate.format(formatter)).lt(endDate.format(formatter));
        Query query = new Query(criteria);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM