简体   繁体   中英

Range in MongoDB find command for pagination

Can I implement any command of MongoDb to find the data of specific range.

For example- I have 100 items in database, I want to first get top 10 items range 1-10, then I want to get next 10 items range 11-20 and so on.

We can do this using skip() and limit()

MongoDB natively supports the paging operation using the skip() and limit() commands. The skip(n) directive tells MongoDB that it should skip 'n' results, and the limit(n) directive instructs MongoDB that it should limit the result length to 'n' results. Typically, you'll be using the skip() and limit() directives with your cursor - but to illustrate the scenario, we provide console commands that would achieve the same results. Also, for brevity of code, the limits-checking code is also excluded:

//Page 1
db.users.find().limit (10)
//Page 2
db.users.find().skip(10).limit(10)
//Page 3
db.users.find().skip(20).limit(10)

You get the idea. In general, to retrieve page 'n' the code looks like this:

db.users.find().skip(pagesize*(n-1)).limit(pagesize)

https://scalegrid.io/blog/fast-paging-with-mongodb/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM