denniss
denniss

Reputation: 17599

MongoDB and Ruby: runCommand geoNear and sorting by date

So I want to do geoNear using runCommand on mongodb and I want the results to be sorted by date.

I know how to do the first part

db.users.runCommand({'geoNear' :"users",'near' : [-76.483999, 42.402794], 'spherical' : true, 'maxDistance' : 20/6378 })

but how do i get the results such that it is ordered by created_at? If I were to use Mongo gem to do this, the query would look like

User.database.command({'geoNear'=>"users",'near' => [-122, 37]}, 'spherical' => true, 'maxDistance' => 20/6378)

Still, I do not know how to sort it by date. I was considering of using an index on created_at in this case. I have indices on both location and created_at but the results are still not returned by order of created_at date. Does anyone have any clue on how to do this?

Upvotes: 0

Views: 1387

Answers (1)

RameshVel
RameshVel

Reputation: 65877

I dont think its possible to add sort to geonear command, as per the link

Valid options are: "near", "num", "maxDistance", "distanceMultiplier" and "query".

by default it sorted by the distance.

Alternatively you can write your spherical query like this

db.users.find( { loc :  { $nearSphere : [80.21223299999997, 13.034892],$maxDistance:20/6378  } } ).sort({ created_at : -1 } ) //-1 for descending

your ruby mongomapper equivalent might be (not sure, better verify)

Users.where(:loc => {'$nearSphere' => [-122, 37],'$maxDistance'=>20/6378 }).sort(:created_at.desc)

Upvotes: 1

Related Questions