mixmaxhq / mongo-cursor-pagination

Cursor-based pagination for Mongo
https://www.mixmax.com/careers
MIT License
229 stars 72 forks source link

feat: allow custom sort pipeline on aggregate #319

Closed raphaelbs closed 2 years ago

raphaelbs commented 2 years ago

Changes Made

I need to sort by a field that doesn't exist in a given collection, i.e. projecting then sorting. This PR adds the capability of supplying a $sort pipeline direct on the aggregation, as such:

const response = await mongoPaging.aggregate('collection', {
  aggregation: [
    { $match: query },
    { $addFields: { toLowerField: { $toLower: '$name' } } },
    { $sort: { toLowerField: -1} },
  ],
  paginatedField: 'name',
  limit: 10
});

Potential Risks

This PR also changes the order of the $limit and the default $sort operations being inserted in the pipeline to allow insert different pipelines between the $match and the $sort.

Without this change, the aggregation would resolve to:

[
  { $match: { ... } },
  { $sort: { ... } },
  { $limit: { ... } },
  { $addFields: { ... } },
]

Instead of what I need:

[
  { $match: { ... } },
  { $addFields: { ... } },
  { $sort: { ... } },
  { $limit: { ... } },
]

Test Plan

Checklist

raphaelbs commented 2 years ago

Dropped in favor of using https://github.com/mixmaxhq/mongo-cursor-pagination/pull/320