Python MongoDB Sorting

Result Sorting

Please use sort() The method sorts the results in ascending or descending order.

sort() Provide a parameter of "fieldname" (field name) for the method, and provide a parameter of "direction" (direction) for the parameter (ascending is the default direction).

Example

Sort the results in alphabetical order by name:

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)

Run Instance

Descending Sort

Use the value -1 as the second parameter for descending order sorting.

sort("name", 1) # Ascending
sort("name", -1) # Descending

Example

Sort the results in reverse alphabetical order by name:

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)

Run Instance