深度阅读

python mongodb sort by field

作者
作者
2023年08月22日
更新时间
9.92 分钟
阅读时间
0
阅读量

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)

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。