Lesson 18 of 50 – Sorting Documents in MongoDB
36%

Sorting Documents in MongoDB

Sorting means arranging documents in a particular order. In MongoDB, we use the sort() method to display documents in ascending or descending order.

For example, we can sort students by name, age, course, or fee.

1. What Is Sorting?

Sorting arranges records according to the values of a specified field.

Consider these documents in the students collection:

{
    _id: 1,
    name: "Rahul",
    age: 22,
    fee: 5000
}
{
    _id: 2,
    name: "Amit",
    age: 19,
    fee: 6000
}
{
    _id: 3,
    name: "Priya",
    age: 21,
    fee: 4500
}

We can sort these students by name, age, or fee using the sort() method.

2. The sort() Method

The sort() method specifies the order in which MongoDB returns documents.

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

The order value can be:

  • 1 — Ascending order.
  • -1 — Descending order.
Example
db.students.find().sort({ age: 1 })

This displays students in ascending order of age, from the smallest age to the largest.

3. Ascending Order

Ascending order arranges values from lower to higher. For text values, it generally sorts alphabetically.

Sort Students by Age
db.students.find().sort({ age: 1 })
Sort Students by Name
db.students.find().sort({ name: 1 })
Sort Products by Price
db.products.find().sort({ price: 1 })

The last command displays products from lower price to higher price.

4. Descending Order

Descending order arranges values from higher to lower. For text values, it generally reverses alphabetical order.

Sort Students by Age
db.students.find().sort({ age: -1 })
Sort Students by Name
db.students.find().sort({ name: -1 })
Sort Products by Price
db.products.find().sort({ price: -1 })

The last command displays products from higher price to lower price.

5. Sorting by Multiple Fields

MongoDB allows sorting by more than one field. The first field is the primary sort field. The next field is used when values in the earlier field are equal.

Example
db.students.find().sort({
    course: 1,
    age: -1
})

This sorts students by course in ascending order. Within each course, students are sorted by age in descending order.

Another Example
db.employees.find().sort({
    department: 1,
    salary: -1
})

Employees are grouped by department order, and within each department, higher salaries appear first.

6. Sorting with a Filter

We can combine find() and sort() to filter documents and then arrange the matching results.

Example: Find Students Older Than 18
db.students.find(
    { age: { $gt: 18 } }
).sort({ age: 1 })

First, MongoDB selects students whose age is greater than 18. Then it sorts those results by age in ascending order.

Example: Find Expensive Products
db.products.find(
    { price: { $gt: 1000 } }
).sort({ price: -1 })

This displays products priced above 1000, with the most expensive products first.

7. Sorting with Projection

Projection specifies which fields should appear in the returned documents. We can combine projection with sorting.

Example
db.students.find(
    {},
    { _id: 0, name: 1, age: 1 }
).sort({ age: 1 })

This returns only the student's name and age, sorted by age in ascending order. The _id field is excluded.

8. Sorting with limit()

We can use limit() to return only a specified number of sorted documents.

Example: Find the Three Highest-Paid Employees
db.employees.find().sort({
    salary: -1
}).limit(3)

This returns up to three employees with the highest salaries.

Example: Find the Two Cheapest Products
db.products.find().sort({
    price: 1
}).limit(2)

This returns up to two products with the lowest prices.

9. Sorting and Missing Fields

A document may not contain the field used for sorting. MongoDB still returns matching documents, but documents with missing or null values may appear according to MongoDB's sort rules.

Example
db.students.find().sort({ age: 1 })

If some student documents do not have an age field, consider filtering for documents where the field exists:

db.students.find({
    age: { $exists: true }
}).sort({ age: 1 })

10. Important Points to Remember

  • sort({ field: 1 }) sorts in ascending order.
  • sort({ field: -1 }) sorts in descending order.
  • Multiple fields can be used for sorting.
  • find() can be combined with filters, projection, sorting, and limits.
  • Sorting changes the order of query results; it does not modify stored documents.
  • For large collections, suitable indexes can help improve sorting performance.

11. Practical Assignment

Create a collection named practice_sort and insert these sample documents:

db.practice_sort.insertMany([
    {
        _id: 1,
        name: "Rahul",
        age: 22,
        course: "Java",
        fee: 5000
    },
    {
        _id: 2,
        name: "Amit",
        age: 19,
        course: "Python",
        fee: 6000
    },
    {
        _id: 3,
        name: "Priya",
        age: 21,
        course: "Java",
        fee: 4500
    },
    {
        _id: 4,
        name: "Neha",
        age: 20,
        course: "Python",
        fee: 7000
    }
])
Complete these tasks:
  1. Sort all students by age in ascending order.
  2. Sort all students by age in descending order.
  3. Sort students alphabetically by name.
  4. Sort students by fee from highest to lowest.
  5. Sort by course in ascending order and age in descending order.
  6. Find students older than 19 and sort them by age.
  7. Display only the name and fee of each student, sorted by fee.
  8. Find the two students with the highest fees.

Run the insertion command only once, or clear the test collection before inserting the same sample data again.

🧠 Quick Quiz

1. Which value sorts documents in ascending order?




2. Which method limits the number of returned documents?




3. Does sort() modify the stored documents?