Pagination and sorting

It is about iOS app on Swift.
I have a list of entities. Each entity has:

  • _id
  • name
  • surname

My goal is to have pagination (20 items per page) and results should be sorted by name and then surname (like 2 sorting criteria).

My code is next:

let collection = database.collection(withName: "Entity")
var queryFilter: Document = [:]
 let sortingName = NSMutableDictionary()
 sortingName["name"] = 1
 let sortingSurname = NSMutableDictionary()
 sortingSurname["surname"] = 1
 let sorting = [
let newProjection = NSMutableDictionary()
let newOptions = FindOptions(limit: pageSize, projection: newProjection, sorting: sorting)        
**collection.find(filter: queryFilter, options: newOptions) { result in**

I’m using method FIND, but the problem is that I need to find a way how to get next page. I have tried:

  • put greater argument in query by “_id” comparing to the last element of the first page (queryFilter[“_id”] = [“$gt”: .objectId(objectId)]), but I noticed that it doesn’t work because some results are duplicated because their “_id” are greater than the last item “_id” of first page. Expected that MongoDB takes all results, sort them, and then query records by condition “greater than specific id” in a meaning of ordering, but not comparing string value.
  • set greater argument in query by “name” and “surname” of last item of first page, but then there can be a case when “name” is empty, and then “surname” will cut off some entities which should be in the result.

The last my idea is to put in query “$nin” every id of the previous results. Probably the worst way, but may work.
I found many solutions about “skip” argument, but I didn’t find that approach for iOS.
Maybe somebody has any advice?