MongoDB 查询跳过前 5 条记录,只显示最后 5 条
要跳过 MongoDB 中的记录,请使用 skip()。使用它,要仅显示特定数量的记录,请使用 limit()。
让我们创建一个包含文档的集合 −
> db.demo275.insertOne({"Number":10}); { "acknowledged" : true, "insertedId" : ObjectId("5e48eac4dd099650a5401a43") } > db.demo275.insertOne({"Number":12}); { "acknowledged" : true, "insertedId" : ObjectId("5e48eac7dd099650a5401a44") } > db.demo275.insertOne({"Number":6}); { "acknowledged" : true, "insertedId" : ObjectId("5e48eac9dd099650a5401a45") } > db.demo275.insertOne({"Number":1}); { "acknowledged" : true, "insertedId" : ObjectId("5e48eacadd099650a5401a46") } > db.demo275.insertOne({"Number":5}); { "acknowledged" : true, "insertedId" : ObjectId("5e48eacddd099650a5401a47") } > db.demo275.insertOne({"Number":24}); { "acknowledged" : true, "insertedId" : ObjectId("5e48ead0dd099650a5401a48") } > db.demo275.insertOne({"Number":8}); { "acknowledged" : true, "insertedId" : ObjectId("5e48ead6dd099650a5401a49") } > db.demo275.insertOne({"Number":9}); { "acknowledged" : true, "insertedId" : ObjectId("5e48ead8dd099650a5401a4a") } > db.demo275.insertOne({"Number":19}); { "acknowledged" : true, "insertedId" : ObjectId("5e48eadddd099650a5401a4b") } > db.demo275.insertOne({"Number":29}); { "acknowledged" : true, "insertedId" : ObjectId("5e48eae1dd099650a5401a4c") }
使用 find() 方法显示集合中的所有文档 −
> db.demo275.find();
它将产生以下输出 −
{ "_id" : ObjectId("5e48eac4dd099650a5401a43"), "Number" : 10 } { "_id" : ObjectId("5e48eac7dd099650a5401a44"), "Number" : 12 } { "_id" : ObjectId("5e48eac9dd099650a5401a45"), "Number" : 6 } { "_id" : ObjectId("5e48eacadd099650a5401a46"), "Number" : 1 } { "_id" : ObjectId("5e48eacddd099650a5401a47"), "Number" : 5 } { "_id" : ObjectId("5e48ead0dd099650a5401a48"), "Number" : 24 } { "_id" : ObjectId("5e48ead6dd099650a5401a49"), "Number" : 8 } { "_id" : ObjectId("5e48ead8dd099650a5401a4a"), "Number" : 9 } { "_id" : ObjectId("5e48eadddd099650a5401a4b"), "Number" : 19 } { "_id" : ObjectId("5e48eae1dd099650a5401a4c"), "Number" : 29 }
以下查询跳过前 5 条记录,仅显示最后 5 条 −
> db.demo275.find().skip(5).limit(5)
它将产生以下输出 −
{ "_id" : ObjectId("5e48ead0dd099650a5401a48"), "Number" : 24 } { "_id" : ObjectId("5e48ead6dd099650a5401a49"), "Number" : 8 } { "_id" : ObjectId("5e48ead8dd099650a5401a4a"), "Number" : 9 } { "_id" : ObjectId("5e48eadddd099650a5401a4b"), "Number" : 19 } { "_id" : ObjectId("5e48eae1dd099650a5401a4c"), "Number" : 29 }
Advertisements