[SERVER-46298] Support sorting by expressions other than field references Created: 21/Feb/20  Updated: 06/Dec/22

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

Type: New Feature Priority: Minor - P4
Reporter: Thomas Zembowicz Assignee: Backlog - Query Execution
Resolution: Unresolved Votes: 0
Labels: qexec-team
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Duplicate
is duplicated by SERVER-47202 Support $sortByExpr aggregation pipel... Closed
Assigned Teams:
Query Execution
Participants:

 Description   

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" ] } } } ] )



 Comments   
Comment by David Percy [ 24/Nov/20 ]

Another syntax idea:

{$sort: {$expr: <expression>}}

This would be similar to {$match: {$expr: <expression>}}. It would also let you sort by an expression in find()-style queries:

db.c.find().sort({$expr: <expression>})

Generated at Thu Feb 08 05:11:03 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.