Sort

Python Mongodb Python Mongodb

sort()The method can specify sorting in ascending or descending order.

sort() The first parameter of the method is the field to sort, and the second parameter specifies the sorting rule,1either ascending,-1or descending, defaulting to ascending.

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

Sort the alexa field in ascending order:

Example

#!/usr/bin/python3 import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["exampledb"] mycol = mydb["sites"] mydoc = mycol.find().sort("alexa") for x in mydoc: print(x)

The output result is:

Sort the alexa field in descending order:

Example

#!/usr/bin/python3 import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["exampledb"] mycol = mydb["sites"] mydoc = mycol.find().sort("alexa", -1) for x in mydoc: print(x)

The output result is:

Python Mongodb Python Mongodb

Other Extensions