views:

106

answers:

2

If the following is used

Analytic.collection.map_reduce(map, reduce, 
  :query => {:page => subclass_name}, 
  :sort => [[:pageviews, Mongo::DESCENDING]]).find.to_a

it won't sort by pageviews. Alternatively, if it is array of hash:

Analytic.collection.map_reduce(map, reduce, 
  :query => {:page => subclass_name}, 
  :sort => [{:pageviews => Mongo::DESCENDING}]).find.to_a

it won't work either. I think the reason it has to be an array is to specify the first field to sort by, etc. I also tried just a flat array instead of an array of array like in the first code listing up above and it didn't work either.

Is it not working? This is the spec: http://api.mongodb.org/ruby/current/Mongo/Collection.html#map_reduce-instance_method

+1  A: 

What are you trying to do? Sort is really only useful in conjunction with limit: it's applied before the map so you can just MapReduce the latest 20 items or something. If you're trying to sort the results, you can just do a normal sort on the output collection.

kristina
i see. maybe the spec can mention it is before the map, not for the final results. also, why do we need to sort something for the map/reduce? In cases I see the usage of map/reduce, it doesn't matter what order the documents (records) are in.
動靜能量
It's for aggregating a subset of your data. Say you wanted to do an aggregation on the last 500 visits to your site. You could do a MapReduce on your visitors collection with a sort by date and a limit of 500. Without sort, you couldn't really do this.
kristina
A: 

Ok, it is a little bit tricky:

After the map_reduce(), a Mongo::Collection object is returned, but the structure is like:

[{"_id":123.0,"value":{"pageviews":3621.0,"timeOnPage":206024.0}},
 {"_id":1320.0,"value":{"pageviews":6584.0,"timeOnPage":373195.0}},
   ...
]

so to do the sort, it has to be:

Analytic.collection.map_reduce(map, reduce, 
  :query => {:page => subclass_name}).find({}, 
    :sort => [['value.pageviews', Mongo::DESCENDING]])

note the value.pageviews part.

動靜能量