Node.js MongoDB Sort

Node.js MongoDB Sort


Node.js MongoDB sort is a function that allows you to sort the documents in a MongoDB collection based on a specific field or fields. The sort function takes in a JavaScript object as its argument, where the key is the field name, and the value is either 1 for ascending or -1 for descending.

Here is an example of how to use the sort function in Node.js MongoDB:

In this example, we are connecting to a local MongoDB instance, selecting the "mydb" database and the "users" collection. We then use the find() method to retrieve all documents, followed by the sort() method to sort the documents by the 'age' field in ascending order. The result is then logged to the console.

It's also possible to sort by multiple fields by passing an array of fields and their sort order to the sort() method. For example, to sort by age in ascending order, and then by name in descending order:

Keep in mind that sorting a large dataset can have a significant impact on performance, so use it judiciously.