I’m currently using collection.find().sort(Sorts.descending("x", "y")).skip(page * limit).limit(limit)
, but how can I sort by whatever “x” and “y” is added together? (Java)
If I understand correctly your documents have two fields such as:
{ _id : 0 ,
foo : 10 ,
bar : 20 }
{ _id : 1 ,
foo : 5 ,
bar : 35 }
and you want to sort based on the result of adding foo to bar.
I do not think you can do that with find() and sort(). You need aggregation:
set_sum = { "$set" : { "_sum" : { "$sum" : [ "$foo" , "$bar" ] } } }
sort_sum = { "$sort" : { "_sum" : -1 } }
skip = { "$skip" : page * limit }
limit = { "$limit" : limit }
pipeline = [ set_sum , sort_sum , skip , limit ]
I do not use the Builders so I cannot give you the exact syntax but Compass can take the pipeline and export it to Java code that uses the builders.
Since you are sorting on a computed value a collection scan will be performed. You might want to store the sum permanently and have an index if you have performance issues.
Thanks you, that worked… Also thanks for mentioning that Compass can do that… Wouldn’t have been able to figure it out without that ._:
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.