From a3dec0c31444909e692cdb9b32f8e6c7640c022c Mon Sep 17 00:00:00 2001 From: Luce Carter Date: Thu, 13 Nov 2025 13:42:12 +0000 Subject: [PATCH] Refactor aggregation pipeline to use $project --- docs/50-aggregation/3-sort-limit.mdx | 45 +++++++++++++++------------- 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/docs/50-aggregation/3-sort-limit.mdx b/docs/50-aggregation/3-sort-limit.mdx index ad2c931..fada0ed 100644 --- a/docs/50-aggregation/3-sort-limit.mdx +++ b/docs/50-aggregation/3-sort-limit.mdx @@ -88,27 +88,30 @@ Learn [when to use $addFields over $project](https://www.practical-mongodb-aggre ```js - await books.aggregate([ - { - $match: { year: { $gt: 2000 } } - }, - { - $match: { - authors: { $exists: true }, - } - }, - { - $addFields: { - numAuthors: { $size: "$authors" }, - } - }, - { - $sort: { "numAuthors": -1 } - }, - { - $limit: 1 - } - ]).toArray(); + await books.aggregate([ + { + $match: { year: { $gt: 2000 } } + }, + { + $match: { + authors: { $exists: true } + } + }, + { + $project: { + title: 1, + year: 1, + authors: 1, + numAuthors: { $size: "$authors" } + } + }, + { + $sort: { numAuthors: -1 } + }, + { + $limit: 1 + } +]).toArray(); ```