Python MongoDB Sort

In MongoDB, you can sort the results of a query using the sort() method. Sorting is based on one or more fields in the documents, and you can sort in either ascending (1) or descending (-1) order.

Syntax of the sort() Method:

collection.find(query).sort(field, direction)
  • field: The name of the field to sort by.
  • direction: Use 1 for ascending order and -1 for descending order.

You can also sort by multiple fields by passing a list of tuples (field, direction).

Example: Sorting Query Results in MongoDB Using Python

Step 1: Connect to MongoDB and Select a Database and Collection

import pymongo

# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = client["mydatabase"]
mycol = mydb["customers"]

Step 2: Inserting Sample Data (Optional)

# Insert sample data into the collection
mycol.insert_many([
    { "name": "John", "age": 28, "address": "123 Elm Street" },
    { "name": "Amy", "age": 32, "address": "456 Oak Street" },
    { "name": "Mark", "age": 25, "address": "789 Maple Avenue" },
    { "name": "Sara", "age": 24, "address": "101 Pine Road" }
])

1. Sorting by a Single Field (Ascending Order)

To sort the results by a single field in ascending order (1):

# Sort by 'age' in ascending order
results = mycol.find().sort("age", 1)

# Print the sorted documents
for doc in results:
    print(doc)

Output:

{ 'name': 'Sara', 'age': 24, 'address': '101 Pine Road' }
{ 'name': 'Mark', 'age': 25, 'address': '789 Maple Avenue' }
{ 'name': 'John', 'age': 28, 'address': '123 Elm Street' }
{ 'name': 'Amy', 'age': 32, 'address': '456 Oak Street' }

2. Sorting by a Single Field (Descending Order)

To sort the results by a single field in descending order (-1):

# Sort by 'age' in descending order
results = mycol.find().sort("age", -1)

for doc in results:
    print(doc)

Output:

{ 'name': 'Amy', 'age': 32, 'address': '456 Oak Street' }
{ 'name': 'John', 'age': 28, 'address': '123 Elm Street' }
{ 'name': 'Mark', 'age': 25, 'address': '789 Maple Avenue' }
{ 'name': 'Sara', 'age': 24, 'address': '101 Pine Road' }

3. Sorting by Multiple Fields

You can sort by multiple fields by passing a list of tuples, where each tuple contains a field and a direction.

For example, to sort first by age (ascending) and then by name (descending):

# Sort by 'age' ascending, and by 'name' descending
results = mycol.find().sort([("age", 1), ("name", -1)])

for doc in results:
    print(doc)

Output:

{ 'name': 'Sara', 'age': 24, 'address': '101 Pine Road' }
{ 'name': 'Mark', 'age': 25, 'address': '789 Maple Avenue' }
{ 'name': 'John', 'age': 28, 'address': '123 Elm Street' }
{ 'name': 'Amy', 'age': 32, 'address': '456 Oak Street' }

Here, the results are sorted by age in ascending order. If two documents have the same age, they are sorted by name in descending order.

4. Sorting with a Query

You can combine sorting with a query to first filter the documents and then sort the results.

For example, to find all documents where age is greater than 25 and sort the results by name in ascending order:

# Query: Find documents where 'age' is greater than 25, sorted by 'name'
query = { "age": { "$gt": 25 } }
results = mycol.find(query).sort("name", 1)

for doc in results:
    print(doc)

Output:

{ 'name': 'Amy', 'age': 32, 'address': '456 Oak Street' }
{ 'name': 'John', 'age': 28, 'address': '123 Elm Street' }

Summary:

  • Ascending Order: Use sort(field, 1) to sort in ascending order.
  • Descending Order: Use sort(field, -1) to sort in descending order.
  • Multiple Fields: Use sort([(field1, direction1), (field2, direction2)]) to sort by multiple fields.
  • Query + Sort: You can combine sorting with a query by applying sort() after find().
Leave a Reply 0

Your email address will not be published. Required fields are marked *