MongoDB方法limit和skip

在web开发过程中,我们肯定会遇到分页功能,如果是mysql我们主要是利用他的limit和offset语法,那么mongodb有类似的功能吗,答案是肯定的,mongodb有对应的limitskip方法

1.limit()方法

语法

db.collection.find().limit(NUMBER)

实例

> db.lesson.insertMany([{"name":"lua", "price":"$20.00"}, {"name":"Go", "price":"$30.00"}, {"name":"python", "price":"$40.00"}])
{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("5c78d839b881b2c3b7328602"),
        ObjectId("5c78d839b881b2c3b7328603"),
        ObjectId("5c78d839b881b2c3b7328604")
    ]
}
> db.lesson.find().limit(2)
{ "_id" : ObjectId("5c78d839b881b2c3b7328602"), "name" : "lua", "price" : "$20.00" }
{ "_id" : ObjectId("5c78d839b881b2c3b7328603"), "name" : "Go", "price" : "$30.00" }

2.skip()方法

语法

db.collection.find().skip(NUMBER)

实例

> db.lesson.find().skip(1)
{ "_id" : ObjectId("5c78d839b881b2c3b7328603"), "name" : "Go", "price" : "$30.00" }
{ "_id" : ObjectId("5c78d839b881b2c3b7328604"), "name" : "python", "price" : "$40.00" }

结合使用

> db.lesson.find().skip(1).limit(1)
{ "_id" : ObjectId("5c78d839b881b2c3b7328603"), "name" : "Go", "price" : "$30.00" }
> db.lesson.find().limit(1).skip(1)
{ "_id" : ObjectId("5c78d839b881b2c3b7328603"), "name" : "Go", "price" : "$30.00" }

先后顺序没有关系

你可能感兴趣的:(MongoDB方法limit和skip)