MongoDB Sort

Order your query results in ascending or descending order

📊 Sorting Results

Sorting allows you to organize query results in a specific order. You can sort by any field in ascending (1) or descending (-1) order, and even sort by multiple fields.


import pymongo

client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["store"]
products = db["products"]

# Sort by price (ascending)
cheap_first = products.find().sort("price", 1)
for product in cheap_first:
    print(f"{product['name']}: ${product['price']}")
                                    
1
Ascending
-1
Descending
Multi
Field Sort

Sort Types

⬆️

Ascending

Sort from lowest to highest

# Sort by price (low to high)
products.find().sort("price", 1)
⬇️

Descending

Sort from highest to lowest

# Sort by price (high to low)
products.find().sort("price", -1)
📝

Text Sort

Sort alphabetically

# Sort by name (A to Z)
products.find().sort("name", 1)
🔢

Multiple Fields

Sort by multiple criteria

# Sort by category, then price
products.find().sort([("category", 1), ("price", -1)])

Basic Sorting

Sort documents by a single field

import pymongo

client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["shop"]
products = db["products"]

# Sort by price - cheapest first
print("Products by price (low to high):")
cheap_first = products.find().sort("price", 1)
for item in cheap_first:
    print(f"- {item['name']}: ${item['price']}")

# Sort by price - most expensive first
print("\nProducts by price (high to low):")
expensive_first = products.find().sort("price", -1)
for item in expensive_first:
    print(f"- {item['name']}: ${item['price']}")

# Sort by name alphabetically
print("\nProducts by name (A to Z):")
alphabetical = products.find().sort("name", 1)
for item in alphabetical:
    print(f"- {item['name']}")

Multiple Field Sorting

Sort by multiple fields with different orders

# Sort by category first, then by price within each category
print("Products by category, then price:")
multi_sort = products.find().sort([
    ("category", 1),    # Category A to Z
    ("price", -1)       # Price high to low within category
])

current_category = ""
for item in multi_sort:
    if item['category'] != current_category:
        current_category = item['category']
        print(f"\n{current_category.upper()}:")
    print(f"  - {item['name']}: ${item['price']}")

# Sort by stock status, then by name
print("\nProducts by stock status, then name:")
stock_sort = products.find().sort([
    ("in_stock", -1),   # In stock items first
    ("name", 1)         # Then alphabetically
])

for item in stock_sort:
    status = "✅ In Stock" if item.get('in_stock', False) else "❌ Out of Stock"
    print(f"- {item['name']} ({status})")

Sorting with Queries

Combine filtering and sorting

# Find electronics under $200, sorted by price
print("Affordable electronics (under $200):")
affordable_electronics = products.find({
    "$and": [
        {"category": "electronics"},
        {"price": {"$lt": 200}}
    ]
}).sort("price", 1)

for item in affordable_electronics:
    print(f"- {item['name']}: ${item['price']}")

# Find books, sorted by rating (highest first)
print("\nBooks by rating:")
top_books = products.find({
    "category": "books"
}).sort("rating", -1)

for item in top_books:
    rating = item.get('rating', 'No rating')
    print(f"- {item['name']}: {rating}⭐")

# Find products on sale, sorted by discount percentage
print("\nSale items by discount:")
sale_items = products.find({
    "on_sale": True
}).sort("discount_percent", -1)

for item in sale_items:
    discount = item.get('discount_percent', 0)
    print(f"- {item['name']}: {discount}% off")

Practical Sorting Examples

Real-world sorting scenarios

# E-commerce: Show best-selling products first
def show_bestsellers():
    bestsellers = products.find().sort("sales_count", -1).limit(5)
    
    print("Top 5 Best Sellers:")
    for i, item in enumerate(bestsellers, 1):
        sales = item.get('sales_count', 0)
        print(f"{i}. {item['name']} - {sales} sold")

# User dashboard: Recent orders first
def show_recent_orders():
    orders = db["orders"]
    recent = orders.find().sort("order_date", -1).limit(10)
    
    print("Recent Orders:")
    for order in recent:
        date = order.get('order_date', 'Unknown date')
        total = order.get('total', 0)
        print(f"- Order #{order.get('_id')}: ${total} on {date}")

# Product catalog: Sort by user preference
def sort_by_preference(sort_by="price", order="asc"):
    direction = 1 if order == "asc" else -1
    
    print(f"Products sorted by {sort_by} ({order}):")
    sorted_products = products.find().sort(sort_by, direction).limit(5)
    
    for item in sorted_products:
        value = item.get(sort_by, 'N/A')
        print(f"- {item['name']}: {sort_by} = {value}")

# Run examples
show_bestsellers()
show_recent_orders()
sort_by_preference("rating", "desc")

🧠 Test Your Knowledge

Which value sorts in descending order?

How do you sort by multiple fields?

What does .sort("name", 1) do?