Python MongoDB Sort (original) (raw)

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:

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.

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

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.

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)

`