You can do this in Aggregation Framework using $project
to create a new computed field "on the fly" and then $sort
to order results by that field.
db.collection.aggregate( [
{$project: {Id1:1, Id2:1, Id3:1, Content:1,
newField:{$add:[ {$multiply:[ {$add: ["$Id1, "$Id2"]}, 10]}, "$Id3"} } },
{$sort: {newField:1} }
] );
Note that since you cannot index a computed value, this sort will happen in memory and therefore if your collection is very large, this will likely fail due to restriction that your aggregation framework cannot use more than 10% of available RAM. Adding a $limit
stage after $sort
will allow a more efficient and less RAM intensive sort.
If this is a sort of operation you will be doing frequently, you may want to store this computed value as a field in the document (then you can index it and search/sort by it efficiently). If the computations are frequently changing, then aggregation is the way to go.