Easy Tutorial
❮ Python Os Lchflags Ref Random Randrange ❯

Sorting

The sort() method allows you to specify ascending or descending order for sorting.

The sort() method takes the first parameter as the field to sort by, and the second parameter specifies the sorting rule. 1 indicates ascending order, -1 indicates descending order, with ascending being the default.

The test data used in this article is as follows (click on the image to view a larger version):

Sorting the field "alexa" in ascending order:

Example

#!/usr/bin/python3

import pymongo

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

mydoc = mycol.find().sort("alexa")
for x in mydoc:
  print(x)

Output result:

Sorting the field "alexa" in descending order:

Example

#!/usr/bin/python3

import pymongo

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

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

for x in mydoc:
  print(x)

Output result:

Python Mongodb

❮ Python Os Lchflags Ref Random Randrange ❯