1

By default, I can use _id value in find() and sort() to skip documents. But, I am sorting using a different field. And hence the documents will be randomly sorted based on _id value.

I am looking for something equivalent of this

db.collection("cities")
                .orderBy("population")
                .startAfter(lastVisible)
                .limit(25);

Couldn't find an equivalent option in mongodb documentation. Kindly help with this query. Thanks in advance.

Sethuraman Srinivasan
  • 1,528
  • 1
  • 20
  • 34

1 Answers1

3

Similar query in MongoDB would be:

db.collection('cities')
  .find({population: {$gt: lastVisible}})
  .sort({population: 1})
  .limit(25)

of course the actual query will depend on other things, but in general it will look like that. Create an index on population to ensure the query won't be a collection scan.

See $gt and Create Indexes to Support Your Queries

Note 1: If you're new to MongoDB, please take a look at free courses in MongoDB University to learn more about MongoDB.

Note 2: Don't use skip+limit for paging. This is a known anti-pattern. See MongoDB - paging and Paging with the Bucket Pattern for more information.

kevinadi
  • 13,365
  • 3
  • 33
  • 49