Sorting
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 rule,1 is ascending,-1 is descending, default is ascending.
The test data used in this article is as follows (click the image to view full size):
Sort the alexa field in ascending order:
Example
#!/usr/bin/python3
import
pymongo
myclient
=
pymongo
.
MongoClient
(
"
mongodb://localhost:27017/
"
)
mydb
=
myclient
[
"
runoobdb
"
]
mycol
=
mydb
[
"
sites
"
]
mydoc
=
mycol
.
find
(
)
.
sort
(
"
alexa
"
)
for
x
in
mydoc
:
(
x
)
The output is:

Sort the alexa field in descending order:
Example
#!/usr/bin/python3
import
pymongo
myclient
=
pymongo
.
MongoClient
(
"
mongodb://localhost:27017/
"
)
mydb
=
myclient
[
"
runoobdb
"
]
mycol
=
mydb
[
"
sites
"
]
mydoc
=
mycol
.
find
(
)
.
sort
(
"
alexa
"
, -
1
)
for
x
in
mydoc
:
(
x
)
The output is:

Python Mongodb