![]() |
VOOZH | about |
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.
collection.find().sort(field, direction)
Parameter:
Let's explore some Examples to understand it.
This Example sorts documents in the names collection by the "id" field in ascending order using PyMongo.
Output
Explanation: find().sort("id", 1) retrieves all documents from the "names" collection and sorts them in ascending order by the "id" field.
This code retrieves documents from the names collection sorting them by the "name" field in descending order using PyMongo.
Output :
Explanation: find().sort("name", -1) retrieves all documents from the "names" collection and sorts them in descending order by the "name" field.
Related Article: