Coverage for docs_src / tutorial / find_and_sort / tutorial000.py: 100%
47 statements
« prev ^ index » next coverage.py v7.12.0, created at 2025-12-07 08:37 +0000
« prev ^ index » next coverage.py v7.12.0, created at 2025-12-07 08:37 +0000
1import os 1abcdef
2from typing import Optional 1abcdef
4from mongodb_odm import ( 1abcdef
5 ASCENDING,
6 DESCENDING,
7 Document,
8 IndexModel,
9 apply_indexes,
10 connect,
11)
14class Player(Document): 1abcdef
15 name: str 1abcdef
16 country_code: str 1abcdef
17 rating: Optional[int] = None 1abcdef
19 class ODMConfig(Document.ODMConfig): 1abcdef
20 indexes = [ 1abcdef
21 IndexModel([("rating", ASCENDING)]),
22 ]
25def configuration(): 1abcdef
26 connect(os.environ.get("MONGO_URL", "mongodb://localhost:27017/testdb")) 1abcdef
27 apply_indexes() 1abcdef
30def create_players(): 1abcdef
31 Player(name="Pelé", country_code="BRA", rating=98).create() 1abcdef
32 Player(name="Diego Maradona", country_code="ARG", rating=97).create() 1abcdef
33 Player(name="Zinedine Zidane", country_code="FRA", rating=94).create() 1abcdef
34 Player(name="Ronaldo", country_code="BRA", rating=94).create() 1abcdef
35 Player(name="Neymar", country_code="BRA", rating=89).create() 1abcdef
36 Player(name="Lionel Messi", country_code="ARG", rating=91).create() 1abcdef
37 Player(name="Ángel Di María", country_code="ARG", rating=84).create() 1abcdef
38 Player(name="Karim Benzema", country_code="FRA", rating=89).create() 1abcdef
39 Player(name="Antoine Griezmann", country_code="FRA", rating=85).create() 1abcdef
40 Player(name="Kylian Mbappé", country_code="FRA", rating=91).create() 1abcdef
41 Player(name="Gerd Müller", country_code="GER").create() 1abcdef
42 Player(name="Miroslav Klose", country_code="GER", rating=91).create() 1abcdef
43 Player(name="Thomas Müller", country_code="GER", rating=87).create() 1abcdef
44 Player(name="Cristiano Ronaldo", country_code="POR", rating=87).create() 1abcdef
45 Player(name="Eusébio", country_code="POR", rating=93).create() 1abcdef
46 Player(name="Diogo Jota", country_code="POR", rating=85).create() 1abcdef
47 Player(name="David Beckham", country_code="ENG", rating=89).create() 1abcdef
48 Player(name="Wayne Rooney", country_code="ENG", rating=80).create() 1abcdef
49 Player(name="Harry Kane", country_code="ENG", rating=89).create() 1abcdef
52def sort_by_id_desc(): 1abcdef
53 players = Player.find(sort=Player.rating) 1abcdef
54 for player in players: 1abcdef
55 print(player) 1abcdef
56 print() 1abcdef
59def sort_with_multiple_key(): 1abcdef
60 players = Player.find( 1abcdef
61 sort=[(Player.rating, ASCENDING), (Player.country_code, DESCENDING)]
62 )
63 for player in players: 1abcdef
64 print(player) 1abcdef
65 print() 1abcdef
68def main(): 1abcdef
69 configuration() 1abcdef
70 create_players() 1abcdef
72 sort_by_id_desc() 1abcdef
73 sort_with_multiple_key() 1abcdef
76if __name__ == "__main__": 1abcdef
77 main()