Sắp xếp kết quả MongoDB bằng Spring Boot với MongoTemplate

Aug 16 2020

Mục đích

Tôi muốn có truy vấn này:

db.getCollection("employees").find().sort({
  hire_date: 1
}).limit(10)

được viết bằng MongoTemplate trong Spring Boot.

Nghiên cứu

Tôi đã thấy nhiều bài đăng và trang web về sắp xếp như vd

  • https://www.baeldung.com/java-mongodb-aggregations
  • Spring + MongoDB - MongoTemplate + Truy vấn tiêu chí
  • Sắp xếp truy vấn Spring MongoDB

Nỗ lực

Tôi đã thử nhiều cách nhưng tôi vẫn không thể tìm ra cách tôi có thể thực hiện điều này. Một số điều tôi đã thử được liệt kê bên dưới:

@Service
public class MongoService {

    @Autowired
    private MongoTemplate mongoTemplate;

    public Document simpleQuery() {

        // 1st
        mongoTemplate.aggregate(Arrays.asList(
                sort(Sorts.ascending("hire_date")),
                limit(10)
        ));

        // 2nd
        mongoTemplate.findAll(Employee.class).sort(new BasicDBObject("hire_date", 1));

        // 3rd
        mongoTemplate.findAll(Employee.class).sort((o1, o2) -> o1.getHire_date() > o2.getHire_date());

        // and more...
    }
}

Tôi đoán giải pháp có thể khá đơn giản, giống như chính truy vấn, nhưng đây là những bước đầu tiên của tôi trên loại cơ sở đó. Cảm ơn bạn trước vì bất kỳ sự giúp đỡ nào về vấn đề này.

Trả lời

1 varman Aug 17 2020 at 00:22

Thử cái này,

Aggregation aggregation = Aggregation.newAggregation(
    sort(Sort.Direction.ASC, "hire_date"),
    limit(10)
).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());

mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(Employee.class), Object.class).getMappedResults();
Gibbs Aug 17 2020 at 00:23

Bạn có thể làm như bên dưới.

  1. Bạn cần một phần truy vấn
//As you need to match all
Query query = new Query()
  1. Bạn cần thêm tùy chọn sắp xếp
//You need to use Sort class with sorting order, field name to be used for sorting
query.with(new Sort(Sort.Direction.ASC, "hire_date"));
  1. Bạn cần thêm tùy chọn phân trang
final Pageable pageableRequest = PageRequest.of(0, 10);
query.with(pageableRequest);
  1. Bạn cần thêm một mô hình
mongoTemplate(query, Employee.class)

Tham khảo mẫu

Một câu trả lời hữu ích khác