I have a really simple Mongodb collection e.g.
{ "_id" : ObjectId("objid"), "url" : "http://mydomain.com", "datestamp" : ISODate("2012-03-17T02:00:45.119Z"), "totalcount" : 1 }
I’m trying to query the collection to return items in descending order as follows:
@globallinks = Mongo::Connection.new.db("mydb").collection("mycollect")
@toplinks = @globallinks.find({}, :sort => ["totalcount", Mongo::DESCENDING], :limit => 100)
This query does not return items in desc order. I know for a fact by scanning through the result set that records look to be unsorted.
Does anyone have any ideas?
What you’re doing works fine for me and it should work.
However, if you only have a limited number of
totalcountvalues then you will get a result set that looks random. Consider a collection where mosttotalcountvalues are 2:Now we sort it by
totalcount(and only bytotalcount):Now we apply a
:limitthat just happens to leave us with onlytotalcount == 2values:Do you notice how the
otherordering looks random? But, if we add a secondary sort key, we’ll get something that looks sorted:totalcountsounds like something that wouldn’t have that many values and would at the very least contain many duplicate values. The:limitis applied after the:sortso it can easily select results with only one or two values fortotalcount. Without a secondary sort key, you can get results that look random even though they are (partially) sorted.Any time you use a sort key that can have duplicated values you usually want to include a secondary sort key to sensibly sort things within the primary groups.