Introduction to MongoDB cursor.sort() Method

MongoDB is a popular NoSQL database that provides various methods for querying and manipulating data. Among them, the sort() method is used to sort query results and can sort in ascending or descending order based on the specified field.

Syntax

The basic syntax of the sort() method is as follows:

db.collection.find().sort({ field: order })

Here, db.collection refers to the collection to be queried, field refers to the field to be sorted, and order represents the order of sorting. The value of order is 1 or -1, representing ascending and descending order, respectively.

Use Cases

The sort() method is suitable for scenarios where query results need to be sorted, such as sorting student scores from high to low or sorting articles by timestamp.

Examples

We will demonstrate the usage of the sort() method through two examples.

Example 1

Suppose we have a student scorecard that includes the student’s name, age, and score. Now we want to sort the student scores in descending order based on their score. We can use the following code:

use test
db.scores.find().sort({score: -1})

Here, test is the database we want to query, and scores is the collection containing student score information. The above code will sort all student scores in descending order based on their score and output the result to the console.

Example 2

Suppose we have a collection of articles that includes the article’s title, publication date, and content. Now we want to sort the articles by publication date. We can use the following code:

use test
db.articles.find().sort({published_at: 1})

The above code will sort all articles in ascending order based on their publication date and output the result to the console.

Conclusion

The sort() method is one of the commonly used methods in MongoDB. It can sort query results, making the results more ordered and meaningful. When using the sort() method, it is important to specify the correct sorting field and order to obtain the expected results.