Friday, 23 October 2020

How to Sort Records in MongoDB? | MongoDB Tutorial for Beginners

🚀 Master MongoDB with Ram N Java!

Want to level up your database skills? Subscribe now for high-quality, beginner-friendly tech tutorials that make complex coding simple and actionable!

🔔 JOIN THE COMMUNITY NOW

How to Sort Records in MongoDB

In any application, presenting data in a logical order is crucial. Whether you're showing the latest products or ranking players by score, you need a way to organize your data. In MongoDB, this is achieved using the powerful sort() method.

The Basics of Sorting

The sort() method in MongoDB takes a document that specifies the fields you want to sort by and the direction of the sort. This method is typically appended to a find() query to organize the results before they are returned to you.

Sorting Directions Explained

There are two primary directions you can sort your documents:

  • Ascending (1): Sorts data from lowest to highest (e.g., A-Z or 1-10).
  • Descending (-1): Sorts data from highest to lowest (e.g., Z-A or 10-1).

💡 Quick Example

To sort a collection of users by age from oldest to youngest, you would use: db.users.find().sort({ age: -1 })

Continue Your MongoDB Journey:

2 comments:

Tutorials