1+ # start-models
2+ from django .db import models
3+ from django_mongodb_backend .fields import ArrayField
4+ from django_mongodb_backend .managers import MongoManager
5+
6+ class Movie (models .Model ):
7+ title = models .CharField (max_length = 200 )
8+ plot = models .TextField (blank = True )
9+ runtime = models .IntegerField (default = 0 )
10+ released = models .DateTimeField ("release date" , null = True , blank = True )
11+ genres = ArrayField (models .CharField (max_length = 100 ), null = True , blank = True )
12+ objects = MongoManager ()
13+
14+ class Meta :
15+ db_table = "movies"
16+ managed = False
17+
18+ def __str__ (self ):
19+ return self .title
20+
21+ class Theater (models .Model ):
22+ theaterId = models .IntegerField (default = 0 )
23+ objects = MongoManager ()
24+
25+ class Meta :
26+ db_table = "theaters"
27+ managed = False
28+
29+ def __str__ (self ):
30+ return self .theaterId
31+ # end-models
32+
33+ # start-filter-project
34+ movies = Movie .objects .raw_aggregate ([
35+ {"$match" : {"title" : "The Parent Trap" }},
36+ {"$project" : {
37+ "title" : 1 ,
38+ "released" : 1
39+ }
40+ }])
41+
42+ for m in movies :
43+ print (f"Plot of { m .title } , released on { m .released } : { m .plot } \n " )
44+ # end-filter-project
45+
46+ # start-atlas-search
47+ movies = Movie .objects .raw_aggregate ([
48+ {
49+ "$search" : {
50+ "index" : "<search-index-name>" ,
51+ "phrase" : {
52+ "path" : "plot" ,
53+ "query" : "whirlwind romance" ,
54+ "slop" : 3
55+ },
56+ "highlight" : {
57+ "path" : "plot"
58+ }
59+ }
60+ },
61+ {
62+ "$project" : {
63+ "title" : 1 ,
64+ "highlight" : {"$meta" : "searchHighlights" }
65+ }
66+ }
67+ ])
68+
69+ for m in movies :
70+ print (f"Title: { m .title } , text match details: { m .highlight } \n " )
71+ # end-atlas-search
72+
73+ # start-geo
74+ chicago_bounds = {
75+ "type" : "Polygon" ,
76+ "coordinates" : [[
77+ [- 87.851 , 41.976 ],
78+ [- 87.851 , 41.653 ],
79+ [- 87.651 , 41.653 ],
80+ [- 87.651 , 41.976 ],
81+ [- 87.851 , 41.976 ]
82+ ]]
83+ }
84+
85+ theaters = Theater .objects .raw_aggregate ([
86+ {
87+ "$match" : {
88+ "location.geo" : {
89+ "$geoWithin" : {
90+ "$geometry" : chicago_bounds
91+ }
92+ }
93+ }
94+ },
95+ {
96+ "$project" : {
97+ "theaterId" : 1
98+ }
99+ }
100+ ])
101+
102+ for t in theaters :
103+ print (f"Theater ID: { t .theaterId } " )
104+ # end-geo
0 commit comments