bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Python/Databases in Python
Python•Databases in Python

Python MongoDB Sort

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Python MongoDB Sort?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___ pymongo
3Order

Put the learning moves in the order that makes the concept easiest to apply.

Use the value -1 as the second parameter to sort descending.
The sort() method takes one parameter for "fieldname" and one parameter for "direction" (ascending is the default direction).
Use the sort() method to sort the result in ascending or descending order.

Sort the Result

Use the sort() method to sort the result in ascending or descending order.

The sort() method takes one parameter for "fieldname" and one parameter for "direction" (ascending is the default direction).

Sort the result alphabetically 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 to sort descending.

sort("name", 1) #ascending sort("name", -1) #descending

Example

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)

Previous

Python MySQL Order By

Next

Python MySQL Delete From By