การเรียงลำดับผลลัพธ์ MongoDB โดยใช้ Spring Boot กับ MongoTemplate

Aug 16 2020

เป้าหมาย

ฉันต้องการมีคำถามนี้:

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

เขียนด้วย MongoTemplate ใน Spring Boot

วิจัย

ฉันเคยเห็นโพสต์และไซต์มากมายเกี่ยวกับการเรียงลำดับเช่น

  • https://www.baeldung.com/java-mongodb-aggregations
  • Spring + MongoDB - MongoTemplate + Criteria Query
  • การเรียงลำดับการค้นหา Spring MongoDB

ความพยายาม

ฉันลองมาหลายวิธีแล้ว แต่ยังคิดไม่ออกว่าจะทำได้อย่างไร บางสิ่งที่ฉันได้ลองมีดังต่อไปนี้:

@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...
    }
}

วิธีแก้ปัญหาอาจจะค่อนข้างง่ายฉันเดาเหมือนแบบสอบถาม แต่นี่เป็นขั้นตอนแรกของฉันบนพื้นดินแบบนั้น ขอขอบคุณล่วงหน้าสำหรับความช่วยเหลือเกี่ยวกับเรื่องนี้

คำตอบ

1 varman Aug 17 2020 at 00:22

ลองสิ่งนี้

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

คุณสามารถทำได้ดังนี้

  1. คุณต้องการส่วนแบบสอบถาม
//As you need to match all
Query query = new Query()
  1. คุณต้องเพิ่มตัวเลือกการเรียงลำดับ
//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. คุณต้องเพิ่มตัวเลือกการแบ่งหน้า
final Pageable pageableRequest = PageRequest.of(0, 10);
query.with(pageableRequest);
  1. คุณต้องเพิ่มแบบจำลอง
mongoTemplate(query, Employee.class)

อ้างอิงตัวอย่าง

อีกคำตอบที่มีประโยชน์