mongoid/mongoid — Issue #1738: .first and .last add _id field to sort resulting in index miss
Author: olery
Created: 2012-02-21 10:37:02+00:00
State: open

When you call .first on a criteria object it adds the ID field at the end of the sort. This results in, unexpected, index misses.

I expect:

Collection.where(:field_a=>"some_value").desc(:field_b)

to result in the query:

db.collection.find({field_a: "some_value"}).sort({field_b:-1})

This means a compound index on field_a, field_b will actually work.

But if you do:

Collection.where(:field_a=>"some_value").desc(:field_b).first

this actually results in:

db.collection.find({field_a: "some_value"}).sort({field_b:-1, _id:1})

I guess mongo should actually still use the index, but it doesn't.

### Possible solution:

Add limit(1) to the query, return the result(s) and then call first item of the array.