在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();
}
}
注意:在实际使用中,还可以根据需要,为查询结果进行排序、筛选等操作。