python mongodb sort by field

Published on Aug. 22, 2023, 12:12 p.m.

Sort the Result Sort oppress.

Use the sort() method to sort the result.

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

Sort the alphabetical result 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)

Sort descending.

Use the value -1 as the second parameter .

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

db.Account.find().sort("UserName")  
db.Account.find().sort("UserName",pymongo.ASCENDING)   
db.Account.find().sort("UserName",pymongo.DESCENDING)  

Sort the result reverse alphabetically 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)