Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-46298

Support sorting by expressions other than field references

    • Type: Icon: New Feature New Feature
    • Resolution: Unresolved
    • Priority: Icon: Minor - P4 Minor - P4
    • None
    • Affects Version/s: None
    • Component/s: Querying
    • Query Execution, Query Integration

      The $sort stage currently only supports sorting on field references. It would be useful to be able to sort on other user-defined expressions applied to each document, whether in $sort or a new stage like $sortByExpression.

      The only way to emulate this behavior now is to add $project stages on either side of a $sort to compute a new field using an expression, sort on that field, and remove the field. However, this trick isn't well-documented documented and it would probably be better if users could do this without having to modify the documents in the pipeline.

      Possible syntax:

      { $sortByExpr: <aggregation expression>  }
      

      Sort by salesAmount ascending:

      db.users.aggregate( [ { $sortByExpr : { $sum: { $multiply: [ "$price", "$quantity" ] } } } ] )
      

            Assignee:
            Unassigned Unassigned
            Reporter:
            thomas.zembowicz@mongodb.com Thomas Zembowicz
            Votes:
            0 Vote for this issue
            Watchers:
            7 Start watching this issue

              Created:
              Updated: