Python Mongodb Sort
# Python3.x Sorting
[ Python Mongodb](#)
The `sort()` method can specify ascending or descending order.
The first parameter of the `sort()` method is the field to sort by, and the second parameter specifies the sort order. **1** is for ascending order, **-1** is for descending order. The default is ascending order.
**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 = myclientmycol = mydbmydoc = 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 = myclientmycol = mydbmydoc = mycol.find().sort("alexa", -1)for x in mydoc: print(x)
The output result is:
!(#)
[ Python Mongodb](#)
YouTip