[SERVER-72121] Add $top/$bottom/$topN/$bottomN as expressions Created: 14/Dec/22  Updated: 24/Jan/23

Status: Backlog
Project: Core Server
Component/s: Aggregation Framework
Affects Version/s: None
Fix Version/s: None

Type: Task Priority: Minor - P4
Reporter: Katya Kamenieva Assignee: Backlog - Query Execution
Resolution: Unresolved Votes: 0
Labels: expression
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Related
related to SERVER-59149 Add $top/$bottom/$topN/$bottomN as ex... Closed
Assigned Teams:
Query Execution
Participants:

 Description   

It is rather awkward that to get topN array elements, you would do $sortArray+$slice while there's topN accumulator available.

Proposing: 

$topN: {input: <expression resolving to array>, n: <n expression>, sortBy: <spec>}

e.g.:

[
  {
    $set: {
      topThreeOptions: {
        $topN: {
          input: "$options",
          n: 3,
          sortBy: { votes: -1 },
        },
      },
      fiveWatchersAZ: {
        $topN: {
          input: "$watchers",
          n: 5,
          sortBy: 1
        },
      },
    },
  },
]


Generated at Thu Feb 08 06:20:52 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.