在Java中實現MongoDB的分頁查詢,可以按以下步驟進行操作:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.10</version>
</dependency>
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("mydb");
MongoCollection<Document> collection = database.getCollection("mycollection");
int skip = (pageNumber - 1) * pageSize;
FindIterable<Document> documents = collection.find().skip(skip).limit(pageSize);
for (Document document : documents) {
// 操作查詢結果
}
完整的示例代碼如下:
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import java.util.ArrayList;
import java.util.List;
public class PaginationExample {
public static void main(String[] args) {
// 連接到MongoDB服務器
MongoClient mongoClient = new MongoClient("localhost", 27017);
// 連接到數據庫
MongoDatabase database = mongoClient.getDatabase("mydb");
// 連接到集合
MongoCollection<Document> collection = database.getCollection("mycollection");
// 分頁查詢
int pageNumber = 2;
int pageSize = 10;
int skip = (pageNumber - 1) * pageSize;
FindIterable<Document> documents = collection.find().skip(skip).limit(pageSize);
// 遍歷查詢結果
for (Document document : documents) {
System.out.println(document.toJson());
}
// 關閉連接
mongoClient.close();
}
}
注意:在實際使用中,還可以根據需要,為查詢結果進行排序、篩選等操作。