java Spring中MongoDB查询中的日期字段按日和月排序

hts6caw3  于 2023-06-04  发布在  Java
关注(0)|答案(1)|浏览(133)

我想按出生日期字段对查询结果进行排序,但同时存储垃圾年份值。这是因为,我们曾经允许出生年份,但我们不再要求它了。
我在Java中使用Spring,使用MongoDB作为数据库。
数据应该像这样排序:

1. 2004-03-05        7. 2005-01-28
2. 2001-03-03        2. 2001-03-03
3. 2003-12-08        1. 2004-03-05
4. 2015-10-08   ->   6. 1999-07-16
5. 1999-09-24        5. 1999-09-24
6. 1999-07-16        4. 2015-10-08
7. 2005-01-28        3. 2003-12-08

这就是我目前对查询进行排序的方式。我首先按指定的字段sortingField排序,然后按对象的_id排序,这样数据的顺序总是相同的。在我的问题中,sortingField = "dob"

List<Sort.Order> sortList = new ArrayList<>();

sortList.add(
    new Sort.Order(
        sortDirection.compareToIgnoreCase("d") == 0
                ? Sort.Direction.DESC
                : Sort.Direction.ASC,
        sortingField));

sortList.add(new Sort.Order(Sort.Direction.ASC, "_id"));

query.with(Sort.by(sortList));

然后使用List<Customer> = mongoTemplate.find(query, Customer.class);得到结果
这可能吗?

oknrviil

oknrviil1#

Java中的排序...

你可以自己写Comparator ...

Comparator<LocalDate>

如果你写一个自定义的Comparator<LocalDate>,你可以简单地按LocalDate的 * 子单元 * 或 * 部分 * 排序:
MonthDay,它只保存关于月份和月份的信息,并且已经完全按照需要实现了Comparable<MonthDay>

代码示例
public static void main(String[] args) {
    // create the list of Strings to be sorted
    List<String> birthdayStrings = List.of(
                "2004-03-05",
                "2001-03-03",
                "2003-12-08",
                "2015-10-08",
                "1999-09-24",
                "1999-07-16",
                "2005-01-28"
            );
    // map this list to a sortable one by parsing the Strings to LocalDates
    List<LocalDate> birthdays = birthdayStrings.stream()
                                               .map(LocalDate::parse)
                                               .collect(Collectors.toList());
    // print the list once
    birthdays.forEach(System.out::println);
    // print some separator in order to visually separate the unsorted from the sorted result
    System.out.println("—".repeat(12));
    // define a comparator for LocalDates that sorts by month-of-year first, then by day-of-month
    Comparator<LocalDate> monthDayComp = new Comparator<LocalDate>() {
        @Override
        public int compare(LocalDate o1, LocalDate o2) {
            // simply sort by (already comparable) part of the LocalDate: MonthDay
            return MonthDay.from(o1).compareTo(MonthDay.from(o2));
        }
    };
    // sort the list using the comparator
    birthdays.sort(monthDayComp);
    // print the sorted list
    birthdays.forEach(System.out::println);
}
输出
2004-03-05
2001-03-03
2003-12-08
2015-10-08
1999-09-24
1999-07-16
2005-01-28
————————————
2005-01-28
2001-03-03
2004-03-05
1999-07-16
1999-09-24
2015-10-08
2003-12-08

相关问题