如何用 MongoDB 实现分页?
借助 MongoDB 中的 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() 方法显示集合中的所有文档。查询如下所示 −
> 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 }
广告