Question

I have a table with the following rows:

Id1 | Id2 | Id3 | Content

I want to query all data with the following sorting: (Id1 + Id2) * 10 + Id3. Using MySQL I use join with selecting this operation and use it in OrderBy. How to do the same in mongodb?

Was it helpful?

Solution

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.

OTHER TIPS

In mongodb, the sort() operation is not computable - you can only specify fields with an associated integer representing the direction (ascending or descending).

http://docs.mongodb.org/manual/reference/method/cursor.sort/

For the kind of sorting you want to make, you would first have to compute the value (Id1 + Id2) * 10 + Id3 and store it in a separate field of your collection, then subsequently sort by that field in your find() query. That way you could also set an index on the field if needed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top