从MongoDB集合中检索记录时,可以使用skip()方法跳过结果中的记录。
db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
Java MongoDB库提供了一个具有相同名称的方法,以跳过记录,并绕过表示要跳过的记录数的整数值来调用此方法(基于find()方法的结果)。
import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.bson.Document; import com.mongodb.MongoClient; public class SkipRecords { public static void main( String args[] ) { //创建一个MongoDB客户端 MongoClient mongo = new MongoClient( "localhost" , 27017 ); //连接到数据库 MongoDatabase database = mongo.getDatabase("myDatabase"); //创建一个集合对象 MongoCollection<Document>collection = database.getCollection("students"); Document document1 = new Document("name", "Ram").append("age", 26).append("city", "Hyderabad"); Document document2 = new Document("name", "Robert").append("age", 27).append("city", "Vishakhapatnam"); Document document3 = new Document("name", "Rhim").append("age", 30).append("city", "Delhi"); Document document4 = new Document("name", "Radha").append("age", 28).append("city", "Mumbai"); Document document5 = new Document("name", "Ramani").append("age", 45).append("city", "Pune"); //插入创建的文档 List<Document> list = new ArrayList<Document>(); list.add(document1); list.add(document2); list.add(document3); list.add(document4); list.add(document5); collection.insertMany(list); System.out.println("Documents Inserted"); //检索集合对象 collection = database.getCollection("students"); //检索具有限制的文档 FindIterable<Document> iterDoc = collection.find().skip(2); Iterator it = iterDoc.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } }
输出结果
Documents Inserted Documents Inserted Document{{_id=5e8886f97631225872d13217, name=Rhim, age=30, city=Delhi}} Document{{_id=5e8886f97631225872d13218, name=Radha, age=28, city=Mumbai}} Document{{_id=5e8886f97631225872d13219, name=Ramani, age=45, city=Pune}}