Python MongoDB Tutorial – Sorting Documents with PyMongo

Last updated 5 months, 1 week ago | 196 views 75     5

Tags:- Python MongoDB

When working with databases, sorting data is crucial for presenting results in a meaningful order. Whether you're listing users by signup date, prices in ascending order, or names alphabetically, sorting makes your data easier to interpret.

In this tutorial, you’ll learn how to sort documents in MongoDB using Python and PyMongo.


Table of Contents

  1. Introduction to Sorting in MongoDB

  2. Prerequisites

  3. Installing PyMongo

  4. Connecting to MongoDB

  5. Inserting Sample Data

  6. Basic Sorting Using sort()

  7. Sorting in Descending Order

  8. Sorting by Multiple Fields

  9. Sorting with Filters

  10. Complete Working Example

  11. Tips and Common Pitfalls


1. Introduction to Sorting in MongoDB

MongoDB allows you to sort documents using the sort() method. You can sort by:

  • A single field (ascending or descending)

  • Multiple fields (for secondary sorting)

In PyMongo, sorting is achieved using the collection.find().sort() method.


⚙️ 2. Prerequisites

  • Python 3.x

  • MongoDB installed or running on MongoDB Atlas

  • Basic knowledge of Python dictionaries


3. Installing PyMongo

Use pip to install PyMongo:

pip install pymongo

4. Connecting to MongoDB

Connect to a local MongoDB server:

import pymongo

client = pymongo.MongoClient("mongodb://localhost:27017/")

Connect to MongoDB Atlas (Cloud):

client = pymongo.MongoClient("mongodb+srv://<username>:<password>@<cluster>.mongodb.net/?retryWrites=true&w=majority")

5. Inserting Sample Data

Insert a sample collection for sorting:

db = client["mydatabase"]
collection = db["products"]

collection.insert_many([
    {"name": "Laptop", "price": 999, "rating": 4.5},
    {"name": "Phone", "price": 599, "rating": 4.7},
    {"name": "Tablet", "price": 399, "rating": 4.2},
    {"name": "Monitor", "price": 199, "rating": 4.3},
    {"name": "Keyboard", "price": 49, "rating": 4.1}
])

6. Basic Sorting Using sort()

Sort products by price (ascending):

for product in collection.find().sort("price", 1):
    print(product)

Output:

Keyboard → Monitor → Tablet → Phone → Laptop

7. Sorting in Descending Order

Sort products by rating in descending order:

for product in collection.find().sort("rating", -1):
    print(product)

Output:

Phone → Laptop → Monitor → Tablet → Keyboard
  • 1 = Ascending order

  • -1 = Descending order


8. Sorting by Multiple Fields

You can sort by multiple fields by passing a list of tuples.

Example: Sort by rating (desc), then price (asc):

for product in collection.find().sort([("rating", -1), ("price", 1)]):
    print(product)

This is useful when ratings are the same and you want to break ties by price.


9. Sorting with Filters

Combine filtering and sorting:

query = {"price": {"$gt": 100}}
for product in collection.find(query).sort("price", 1):
    print(product)

Output:

Products over $100 sorted by price ascending.


10. Complete Working Example

import pymongo

# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["products"]

# Insert sample data if empty
if collection.count_documents({}) == 0:
    collection.insert_many([
        {"name": "Laptop", "price": 999, "rating": 4.5},
        {"name": "Phone", "price": 599, "rating": 4.7},
        {"name": "Tablet", "price": 399, "rating": 4.2},
        {"name": "Monitor", "price": 199, "rating": 4.3},
        {"name": "Keyboard", "price": 49, "rating": 4.1}
    ])

print("Sorted by price (ascending):")
for p in collection.find().sort("price", 1):
    print(p)

print("\nSorted by rating (descending):")
for p in collection.find().sort("rating", -1):
    print(p)

print("\nSorted by rating DESC then price ASC:")
for p in collection.find().sort([("rating", -1), ("price", 1)]):
    print(p)

11. Tips and Common Pitfalls

Tip / Pitfall Explanation
Use 1 for ascending, -1 for descending Common mistake is passing "asc" or "desc" strings
Sorting large datasets can be slow Use indexing in MongoDB for better performance
Field must exist in all documents Missing fields may result in unexpected order
Combine sort with limit() for pagination Efficiently retrieve top N records

✅ Conclusion

Sorting is essential for readable and organized output in any application. With PyMongo, sorting documents in MongoDB is straightforward using the sort() method. Whether you're sorting by one or multiple fields, ascending or descending, PyMongo offers full flexibility.

Now you're equipped to sort any MongoDB data using Python like a pro!