0

I have the following Mongo database:

db.group:

{id: 1, name:"a"}  // index == 1
{id: 2, name:"b"}  // index == 2
{id: 13, name:"c"} // index == 3
{id: 14, name:"d"} // index == 4
{id: 51, name:"e"} // index == 5
{id: 52, name:"f"} // index == 6
{id: 61, name:"g"} // index == 7
{id: 88, name:"h"} // index == 8

I am implementing pagination and I'd like to return 3 documents, starting from the index 4 (1-based, not zero based), which would be

{id: 14, name:"d"} // index == 4
{id: 51, name:"e"} // index == 5
{id: 52, name:"f"} // index == 6

I know I can use .limit to limit the number of records returned, but how do I say the limit should start from the index 4?

Alexandre Santos
  • 8,170
  • 10
  • 42
  • 64

1 Answers1

2

You can use cursor.skip():

db.getCollection('group').sort({_id: 1}).skip(3).limit(10)

Please note that skip() is not the most efficient as the number increases. You may want to use range based pagination instead:

db.getCollection('group').find({_id: {$gt: 13}}).limit(10)
Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94
  • 3
    Your first example should include an explicit sort order (it looks like that would be by `name`) as the natural order is not guaranteed. See also: [What does Mongo sort on when no sort order is specified?](http://stackoverflow.com/questions/11599069/what-does-mongo-sort-on-when-no-sort-order-is-specified). Also, I expect you'll find that `group` doesn't work well as a collection name from the `mongo` shell since it overlaps with the `group()` function. It's possible to workaround with `db.getCollection()`; your current syntax would result in errors. – Stennie Aug 17 '14 at 12:14
  • I'm here because I also named my collection "group" and failed to call the `find` method in the mongo shell. I think this answer will help more people if it mentions it explicitly. :) – Zheng Liu Sep 21 '18 at 05:28