Which sort to use with a $search stage

If I have a $search stage in an aggregation pipeline, and I want to sort based on a property, is it better or more performant to use the sort inside the $search stage or to add an extra stage with a $sort?

So is 1 better than 2? and why?
1:

[
  {
    $search: {
      index: "v1",
      text: { query: "query", path: "path" },
      sort: { createdAt: -1 },
    },
  },
]

2:

[
  {
    $search: {
      index: "v1",
      text: { query: "query", path: "path" },
    },
  },
  { $sort: { createdAt: -1 } }
]

inside $search for sure. Why? Because stages after $search must consume all the matching documents and operator on them, whereas within $search the sorting is done internally and emitted in the desired order. In the case where all results are being returned without a $limit it may be a closer call, but inside $search would likely always be faster.

1 Like

okay thanks good to know. we always use a $limit stage after the $search stage so that probably will make it even faster.