Last Updated : 04 Jul, 2025
In MongoDB, sorting allows you to arrange documents in a specific order based on one or more fields. Using PyMongo in Python, you can apply the sort() method on a query result to retrieve documents in ascending or descending order. This is helpful when you want results ranked by specific fields.
Syntaxcollection.find().sort(field, direction)
Parameter:
Let's explore some Examples to understand it.
Sample Collection used in this article: Collection used for Example Example 1:This Example sorts documents in the names collection by the "id" field in ascending order using PyMongo.
Python
import pymongo
client = pymongo.MongoClient('localhost', 27017)
db = client["GFG"]
collection = db["names"]
# Sort documents by 'id' in ascending order
sorted_docs = collection.find().sort("id", 1)
# Print sorted documents
for doc in sorted_docs:
print(doc)
Output
Snapshot of Terminal showing Output of sort methodExplanation: find().sort("id", 1) retrieves all documents from the "names" collection and sorts them in ascending order by the "id" field.
Example 2:This code retrieves documents from the names collection sorting them by the "name" field in descending order using PyMongo.
Python
import pymongo
my_client = pymongo.MongoClient('localhost', 27017)
mydb = my_client["gfg"]
mynew = mydb["names"]
# Sort documents by 'name' in descending order
mydoc = mynew.find().sort("name", -1)
# Print the sorted documents
for x in mydoc:
print(x)
Output :
Snapshot of Terminal showing Output of sort methodExplanation: find().sort("name", -1) retrieves all documents from the "names" collection and sorts them in descending order by the "name" field.
Related Article:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4