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