Back to Python Notes
Topic #190

MongoDB Sort

Sorting MongoDB results uses the sort() method with field and direction. It mirrors ORDER BY for document collections.


Sort the Result

Use the sort() method to sort the result in ascending or descending order.

The sort() method takes one parameter for "fieldname" and one parameter for "direction" (ascending is the default direction).

Example

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

mydoc = mycol.find().sort("name")

for x in mydoc:
  print(x)

Sort Descending

Use the value -1 as the second parameter to sort descending.

Note: sort("name", 1) #ascending sort("name", -1) #descending

Example

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

mydoc = mycol.find().sort("name", -1)

for x in mydoc:
  print(x)

Want to go beyond the notes?

Join Coding Now Tech Institute's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

MongoDB Sort – FAQs

Quick answers about learning MongoDB Sort in Python.

This free note from Coding Now Tech Institute explains MongoDB Sort in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on Coding Now Tech Institute, including MongoDB Sort, is 100% free with no signup required.
With focused practice, most students grasp MongoDB Sort in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now