@@ -24,10 +24,46 @@ Some MongoDB-specific ``QuerySet`` methods are available by adding a custom
24
24
25
25
Similar to :meth: `QuerySet.raw()<django.db.models.query.QuerySet.raw> `, but
26
26
instead of a raw SQL query, this method accepts a pipeline that will be passed
27
- to :meth: `pymongo.collection.Collection.aggregate `. The pipeline must return
28
- the necessary fields to construct model instances and may also return
29
- additional fields that will be added as annotations on the models.
27
+ to :meth: `pymongo.collection.Collection.aggregate `.
30
28
31
29
For example, you could write a custom match criteria::
32
30
33
- Post.objects.raw_aggregate([{"$match": {"title": "MongoDB is fun!"}}])
31
+ Question.objects.raw_aggregate([{"$match": {"question_text": "What's up"}}])
32
+
33
+ The pipeline may also return additional fields that will be added as
34
+ annotations on the models::
35
+
36
+ >>> questions = Question.objects.raw_aggregate([{
37
+ ... "$project": {
38
+ ... "question_text": 1,
39
+ ... "pub_date": 1,
40
+ ... "year_published": {"$year": "$pub_date"}
41
+ ... }
42
+ ... }])
43
+ >>> for q in questions:
44
+ ... print(f"{q.question_text} was published in {q.year_published}.")
45
+ ...
46
+ What's up? was published in 2024.
47
+
48
+ Fields may also be left out:
49
+
50
+ >>> Question.objects.raw_aggregate([{" $project" : {" question_text" : 1 }}])
51
+
52
+ The ``Question `` objects returned by this query will be deferred model instances
53
+ (see :meth: `~django.db.models.query.QuerySet.defer() `). This means that the
54
+ fields that are omitted from the query will be loaded on demand. For example::
55
+
56
+ >>> for q in Question.objects.raw_aggregate([{"$project": {"question_text": 1}}]):
57
+ >>> print(
58
+ ... q.question_text, # This will be retrieved by the original query.
59
+ ... q.pub_date, # This will be retrieved on demand.
60
+ ... )
61
+ ...
62
+ What's new 2023-09-03 12:00:00+00:00
63
+ What's up 2024-08-23 20:57:30+00:00
64
+
65
+ From outward appearances, this looks like the query has retrieved both the
66
+ question text and published date. However, this example actually issued three
67
+ queries. Only the question texts were retrieved by the ``raw_aggregate() ``
68
+ query -- the published dates were both retrieved on demand when they were
69
+ printed.
0 commit comments