Skip to content

Commit 3c4e1d9

Browse files
committed
Update sort and limit section
- Change challenge question to year 2000 for more significant sort - Check if authors field exists before getting the size
1 parent 9e4e76f commit 3c4e1d9

File tree

1 file changed

+34
-27
lines changed

1 file changed

+34
-27
lines changed

docs/50-aggregation/3-sort-limit.mdx

Lines changed: 34 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ SELECT * FROM books ORDER BY timestamp DESC LIMIT 5;
7272

7373
## 👐 Challenge
7474

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?
7676

7777
<details>
7878
<summary>Answer</summary>
@@ -89,44 +89,51 @@ Learn [when to use $addFields over $project](https://www.practical-mongodb-aggre
8989
<TabItem value="mongodb-shell" label="Using $project">
9090
```js
9191
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([
11592
{
116-
$match: { year: {$gt: 2010}}
93+
$match: { year: { $gt: 2000 } }
94+
},
95+
{
96+
$match: {
97+
authors: { $exists: true },
98+
}
11799
},
118100
{
119101
$addFields: {
120-
numAuthors: {$size: "$authors"},
102+
numAuthors: { $size: "$authors" },
121103
}
122104
},
123105
{
124-
$sort: { "numAuthors": -1}
106+
$sort: { "numAuthors": -1 }
125107
},
126108
{
127109
$limit: 1
128110
}
129111
]);
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+
]);
130137
```
131138
</TabItem>
132139
</Tabs>

0 commit comments

Comments
 (0)