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 thesort() method on a query result to retrieve documents inascendingordescendingorder. This is helpful when you want results ranked by specific fields.
Syntax
collection.find().sort(field, direction)
Parameter:
- field (str): name of the field to sort
- direction (int): sorting direction, use:1forascending order and-1 fordescendingorder
Let's explore some Examples to understand it.
Sample Collection used in this article:
Collection used for ExampleExample 1:
This Example sorts documents in the names collection by the "id" field inascendingorder using PyMongo.
Pythonimportpymongoclient=pymongo.MongoClient('localhost',27017)db=client["GFG"]collection=db["names"]# Sort documents by 'id' in ascending ordersorted_docs=collection.find().sort("id",1)# Print sorted documentsfordocinsorted_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 inascendingorder by the "id" field.
Example 2:
This code retrieves documents from the names collection sorting them by the "name" field indescendingorder using PyMongo.
Pythonimportpymongomy_client=pymongo.MongoClient('localhost',27017)mydb=my_client["gfg"]mynew=mydb["names"]# Sort documents by 'name' in descending ordermydoc=mynew.find().sort("name",-1)# Print the sorted documentsforxinmydoc: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 indescending order by the "name" field.
Related Article: