VOOZH about

URL: https://www.geeksforgeeks.org/python/python-mongodb-sort/

⇱ Python MongoDB - Sort - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python MongoDB - Sort

Last Updated : 4 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.

Syntax

collection.find().sort(field, direction)

Parameter:

  • field (str): name of the field to sort
  • direction (int): sorting direction, use: 1 for ascending order and -1 for descending order

Let's explore some Examples to understand it.

Sample Collection used in this article:

👁 sort-database
Collection used for Example

Example 1:

This Example sorts documents in the names collection by the "id" field in ascending order using PyMongo.

Output

👁 sort-output1
Snapshot of Terminal showing Output of sort method

Explanation: 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.

Output :

👁 ss
Snapshot of Terminal showing Output of sort method

Explanation: find().sort("name", -1) retrieves all documents from the "names" collection and sorts them in descending order by the "name" field.

Related Article:

Comment
Article Tags: