您可以在limit()
和的帮助下实现分页skip()
。
为了理解这个概念,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.paginationDemo.insertOne({"CustomerName":"Chris","CustomerAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5c949de44cf1f7a64fa4df52") } > db.paginationDemo.insertOne({"CustomerName":"Robert","CustomerAge":26}); { "acknowledged" : true, "insertedId" : ObjectId("5c949df14cf1f7a64fa4df53") } > db.paginationDemo.insertOne({"CustomerName":"David","CustomerAge":24}); { "acknowledged" : true, "insertedId" : ObjectId("5c949dfc4cf1f7a64fa4df54") } > db.paginationDemo.insertOne({"CustomerName":"Carol","CustomerAge":28}); { "acknowledged" : true, "insertedId" : ObjectId("5c949e3e4cf1f7a64fa4df55") } > db.paginationDemo.insertOne({"CustomerName":"Bob","CustomerAge":29}); { "acknowledged" : true, "insertedId" : ObjectId("5c949e474cf1f7a64fa4df56") }
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.paginationDemo.find().pretty();
以下是输出-
{ "_id" : ObjectId("5c949de44cf1f7a64fa4df52"), "CustomerName" : "Chris", "CustomerAge" : 23 } { "_id" : ObjectId("5c949df14cf1f7a64fa4df53"), "CustomerName" : "Robert", "CustomerAge" : 26 } { "_id" : ObjectId("5c949dfc4cf1f7a64fa4df54"), "CustomerName" : "David", "CustomerAge" : 24 } { "_id" : ObjectId("5c949e3e4cf1f7a64fa4df55"), "CustomerName" : "Carol", "CustomerAge" : 28 } { "_id" : ObjectId("5c949e474cf1f7a64fa4df56"), "CustomerName" : "Bob", "CustomerAge" : 29 }
这是与MongoDB分页的查询-
> db.paginationDemo.find().skip(0).limit(3);
以下是输出-
{ "_id" : ObjectId("5c949de44cf1f7a64fa4df52"), "CustomerName" : "Chris", "CustomerAge" : 23 } { "_id" : ObjectId("5c949df14cf1f7a64fa4df53"), "CustomerName" : "Robert", "CustomerAge" : 26 } { "_id" : ObjectId("5c949dfc4cf1f7a64fa4df54"), "CustomerName" : "David", "CustomerAge" : 24 }