Skip to content

Commit a3dec0c

Browse files
authored
Refactor aggregation pipeline to use $project
1 parent d313e22 commit a3dec0c

File tree

1 file changed

+24
-21
lines changed

1 file changed

+24
-21
lines changed

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

Lines changed: 24 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -88,27 +88,30 @@ Learn [when to use $addFields over $project](https://www.practical-mongodb-aggre
8888
<Tabs groupId="aggregations">
8989
<TabItem value="mongodb-shell" label="Using $project">
9090
```js
91-
await books.aggregate([
92-
{
93-
$match: { year: { $gt: 2000 } }
94-
},
95-
{
96-
$match: {
97-
authors: { $exists: true },
98-
}
99-
},
100-
{
101-
$addFields: {
102-
numAuthors: { $size: "$authors" },
103-
}
104-
},
105-
{
106-
$sort: { "numAuthors": -1 }
107-
},
108-
{
109-
$limit: 1
110-
}
111-
]).toArray();
91+
await books.aggregate([
92+
{
93+
$match: { year: { $gt: 2000 } }
94+
},
95+
{
96+
$match: {
97+
authors: { $exists: true }
98+
}
99+
},
100+
{
101+
$project: {
102+
title: 1,
103+
year: 1,
104+
authors: 1,
105+
numAuthors: { $size: "$authors" }
106+
}
107+
},
108+
{
109+
$sort: { numAuthors: -1 }
110+
},
111+
{
112+
$limit: 1
113+
}
114+
]).toArray();
112115
```
113116
</TabItem>
114117
<TabItem value="atlas" label="Using $addFields">

0 commit comments

Comments
 (0)