You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
### Get annual, average and max spending from customers in all cities
32
+
13
33
```SQL
14
34
SELECT
15
35
city,
@@ -35,6 +55,44 @@ GROUP BY city;
35
55
36
56
## Equivalent MongoDB aggregation pipeline
37
57
58
+
59
+
### Get authors’ bios with books that have an average 5-star rating
60
+
61
+
We o through 4 stages:
62
+
- group all the reviews for every book, calculating the average rating.
63
+
- filter out all average ratings other than 5.
64
+
- now we have reviews with 5 stars, but we also want the author bio, so we join with author to get the bio.
65
+
- we add a new field called `bio` with just the author's bio.
66
+
67
+
```js
68
+
db.reviews.aggregate([
69
+
{
70
+
$group: {
71
+
_id:"$bookId",
72
+
averageRating: {
73
+
$avg:"$rating",
74
+
},
75
+
},
76
+
},
77
+
{ $match: { averageRating:5 } },
78
+
{ $lookup: {
79
+
from:"authors",
80
+
localField:"_id",
81
+
foreignField:"books",
82
+
as:"author",
83
+
},
84
+
},
85
+
{$addFields: {
86
+
bio:"$author.bio"
87
+
}},
88
+
])
89
+
90
+
91
+
```
92
+
93
+
94
+
### Get annual, average and max spending from customers in all cities
95
+
38
96
Here we pass three stages: one to return one document per element in the `address` array, and then we filter out to get only the documents that have a `home` address location. Finally, we do the grouping. As we'll see, this can be split and tested separately and resembles our code.
0 commit comments