@@ -72,7 +72,7 @@ SELECT * FROM books ORDER BY timestamp DESC LIMIT 5;
72
72
73
73
## 👐 Challenge
74
74
75
- ### 👐 1. After the year 2010 , which book has the most number of authors?
75
+ ### 👐 1. After the year 2000 , which book has the most number of authors?
76
76
77
77
<details >
78
78
<summary >Answer</summary >
@@ -89,44 +89,51 @@ Learn [when to use $addFields over $project](https://www.practical-mongodb-aggre
89
89
<TabItem value = " mongodb-shell" label = " Using $project" >
90
90
``` js
91
91
db .books .aggregate ([
92
- {
93
- $match: { year: {$gt: 2010 }}
94
- },
95
- {
96
- $project: {
97
- title: 1 ,
98
- authors: 1 ,
99
- numAuthors: {$size: " $authors" },
100
- _id: 0
101
- }
102
- },
103
- {
104
- $sort: { " numAuthors" : - 1 }
105
- },
106
- {
107
- $limit: 1
108
- }
109
- ]);
110
- ```
111
- </TabItem >
112
- <TabItem value = " atlas" label = " Using $addFields" >
113
- ``` js
114
- db .books .aggregate ([
115
92
{
116
- $match: { year: {$gt: 2010 }}
93
+ $match: { year: { $gt: 2000 } }
94
+ },
95
+ {
96
+ $match: {
97
+ authors: { $exists: true },
98
+ }
117
99
},
118
100
{
119
101
$addFields: {
120
- numAuthors: {$size: " $authors" },
102
+ numAuthors: { $size: " $authors" },
121
103
}
122
104
},
123
105
{
124
- $sort: { " numAuthors" : - 1 }
106
+ $sort: { " numAuthors" : - 1 }
125
107
},
126
108
{
127
109
$limit: 1
128
110
}
129
111
]);
112
+ ```
113
+ </TabItem >
114
+ <TabItem value = " atlas" label = " Using $addFields" >
115
+ ``` js
116
+ db .books .aggregate ([
117
+ {
118
+ $match: { year: { $gt: 2000 } }
119
+ },
120
+ {
121
+ $match: {
122
+ authors: { $exists: true },
123
+ }
124
+ },
125
+ {
126
+ $addFields: {
127
+ numAuthors: { $size: " $authors" },
128
+ }
129
+ },
130
+ {
131
+ $sort: { " numAuthors" : - 1 }
132
+ },
133
+ {
134
+ $limit: 1
135
+ }
136
+ ]);
130
137
```
131
138
</TabItem >
132
139
</Tabs >
0 commit comments