MongoRepository 中使用 Limit 和 Skip 的不同方式
瀏覽人數:2,105最近更新:
一、簡介
在 Spring Data 中使用 MongoDB 時, MongoRepository
介面提供了一種使用內建方法與 MongoDB 集合互動的簡單方法。
在這個快速教程中,我們將學習如何在MongoRepository
中使用 limit 和skip。
2. 設定
首先,讓我們建立一個名為StudentRepository
的儲存庫。這是我們儲存學生資訊的地方:
public interface StudentRepository extends MongoRepository<Student, String> {}
然後,我們將一些範例學生記錄新增到此儲存庫。將這些視為練習數據,以幫助我們玩耍和學習:
@Before
public void setUp() {
Student student1 = new Student("A", "Abraham", 15L);
Student student2 = new Student("B", "Usman", 30L);
Student student3 = new Student("C", "David", 20L);
Student student4 = new Student("D", "Tina", 45L);
Student student5 = new Student("E", "Maria", 33L);
studentList = Arrays.asList(student1, student2, student3, student4, student5);
studentRepository.saveAll(studentList);
}
之後,我們將深入研究使用skip和limit來尋找特定學生資訊的細節。
3. 使用Aggregation
管道
聚合管道是處理、轉換和分析資料的強大工具。它的工作原理是將多個階段連結在一起,每個階段執行特定的操作。這些操作包括過濾、分組、排序、分頁等。
讓我們應用限制並跳到一個基本範例:
@Test
public void whenRetrievingAllStudents_thenReturnsCorrectNumberOfRecords() {
// WHEN
List<Student> result = studentRepository.findAll(0L, 5L);
// THEN
assertEquals(5, result.size());
}
上述聚合管道會跳過指定數量的文件並將輸出限制為指定數量。
@Test
public void whenLimitingAndSkipping_thenReturnsLimitedStudents() {
// WHEN
List<Student> result = studentRepository.findAll(3L, 2L);
// THEN
assertEquals(2, result.size());
assertEquals("Tina", result.get(0).getName());
assertEquals("Maria", result.get(1).getName());
}
我們甚至可以在複雜的聚合管道中應用限制和跳過:
@Aggregation(pipeline = {
"{ '$match': { 'id' : ?0 } }",
"{ '$sort' : { 'id' : 1 } }",
"{ '$skip' : ?1 }",
"{ '$limit' : ?2 }"
})
List<Student> findByStudentId(final String studentId, Long skip, Long limit);
這是測試:
@Test
public void whenFilteringById_thenReturnsStudentsMatchingCriteria() {
// WHEN
List<Student> result = studentRepository.findByStudentId("A", 0L, 5L);
// THEN
assertEquals(1, result.size());
assertEquals("Abraham", result.get(0).getName());
}
4. 使用Pageable
在 Spring Data 中, Pageable
是一個接口,表示以分頁方式檢索資料的請求。當從 MongoDB 集合中查詢資料時, Pageable
物件允許我們指定頁碼、頁面大小和排序條件等參數。這對於在應用程式上顯示大型資料集特別有用,因為一次顯示所有項目會很慢。
讓我們探討如何使用Pageable
定義儲存庫方法來實現高效率的資料擷取:
Page<Student> findAll(Pageable pageable);
讓我們新增一個測試:
@Test
public void whenFindByStudentIdUsingPageable_thenReturnsPageOfStudents() {
// GIVEN
Sort sort = Sort.by(Sort.Direction.DESC, "id");
Pageable pageable = PageRequest.of(0, 5, sort);
// WHEN
Page<Student> resultPage = studentRepository.findAll(pageable);
// THEN
assertEquals(5, resultPage.getTotalElements());
assertEquals("Maria", resultPage.getContent().get(0).getName());
}
5. 結論
在這篇短文中,我們探討了MongoRepository
中跳過和限制功能的使用。此外,我們也強調了Pageable
在簡化分頁方面的實用性以及Aggregation
的靈活性,以便更好地控制查詢邏輯或特定的過濾需求。
與往常一樣,所有程式碼片段都可以在 GitHub 上找到。
本作品係原創或者翻譯,採用《署名-非商業性使用-禁止演繹4.0國際》許可協議