Using Sort, Skip, and Limit in MongoDB
In our last tutorial, we queried states where the high temperature was greater than 100 and less than 110. Now we want to query all the records passing an empty object in the find() method. Because we want to sort the results, skip the first two, and limit the return of the results to three, we use a cursor. On the cursor we call sort(…), skip(2), and limit(3) as shown…
The order of these three statement doesn’t matter. But mongodb will always perform them in the order of sort first, skip second, and limit last because that is the only order that makes sense.
The sort() method takes a complicated array of array because we want to first sort descending by temperature, and then sort ascending by state in the event that two states have the same high temperature. The -1 indicates descending, and the 1 indicates ascending. Arrays are used here instead of the usual objects, because arrays are ordered whereas properties in objects are not.