Sorting Result Sets

An important aspect of retrieving documents from a MongoDB database is the ability to get it in a sorted format. Sorting is especially helpful if you are only retrieving a certain number, such as the top 10, or if you are paging the requests. The options object provides the sort option, which allows you to specify the sort order and direction of one or more fields in a document.

You specify the sort option by using an array of [field,<sort_order>] pairs, where sort_order is 1 for ascending and -1 for descending. For example, to sort on the name field descending first and then on the value field ascending, you would use:

sort:[['name':1]['value':-1]]

Listing 15.6 shows how to use the sort option ...

Get Node.js, MongoDB, and AngularJS Web Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.