Andreas Hald
Andreas Hald

Reputation: 215

How to get n documents after _id in sorted collection

i want to use cursor based pagination on a mongodb collection with a sort.

Here's a sample collection

{
  _id: 3,
  name: 'aaa'
},
{
  _id: 2,
  name: 'bbb'
},
{
  _id: 1,
  name: 'ccc'
}

So in my first query, i will sort the collection by name ascending order and limit by 1 the first document will be

{
  _id: 3,
  name: 'aaa'
}

This is where i need help, i now need a query, that sorts the collection by name and returns n documents after the _id:3 but in the sorted collection.

I need it to return

{
  _id: 2,
  name: 'bbb'
}

Essentially it needs to look through the sorted list, find the _id i'm providing, and return ndocuments after that one.

I'm operating inside an aggregation pipeline, and i know i could possibly use $group and create a single document with an array of all the sub documents, then use $filter. but that seems really inelegant, and i'm worried about performance.

Any ideas?

Upvotes: 2

Views: 315

Answers (1)

Joe
Joe

Reputation: 28336

Instead of limit, use the batchsize option with find to get the first document. The command response will also include a cursor ID.

Then use that cursor ID with getMore, and set the batchsize to the number of documents you want in that batch.

Upvotes: 0

Related Questions