sortingmongodbphp-mongodb

How to sort a MongoDB query for a ratio of two fields in every document?


Suppose I have a lot of documents like {'a' : x , 'b' : y}. Suppose x and y are integers. How can I do something like find().sort({'a'/'b'}) ?


Solution

  • You can add third field, result of a/b and sort by it.

    You document will looks like:

    {'a' : x , 'b' : y, c : z} // z = x/y
    

    And you will sort by 'c':

    find().sort({c : 1})