sort property

Map<String, Object>? sort
getter/setter pair

Determines which document the operation modifies if the query selects multiple documents. findAndModify modifies the first document in the sort order specified by this argument.

Starting in MongoDB 4.2 (and 4.0.12+, 3.6.14+, and 3.4.23+), the operation errors if the sort argument is not a document.

In MongoDB, sorts are inherently stable, unless sorting on a field which contains duplicate values:

  • a stable sort is one that returns the same sort order each time it is performed
  • an unstable sort is one that may return a different sort order when performed multiple times

If a stable sort is desired, include at least one field in your sort that contains exclusively unique values. The easiest way to guarantee this is to include the _id field in your sort query.

See Sort Stability for more information.

Implementation

Map<String, Object>? sort;