mongo-hacker
mongo-hacker copied to clipboard
find().first() disables use of indexes
Use of the first() function on a cursor, eg after a find(), without specifying a sort parameter defaults to using $natural which usually disables the use of indexes on the find (but not always for find on _id) . Some other default, or a warning, would be preferable.
As a suggestion, the first() function could short-circuit to one() for the no-parameter case. But I'm not sure that is a valid general solution.
Hey @Boomtime, thanks for filing the issue.
Unless specifying a sort i don't think you would want the database to use an index to get the first document as the database doesn't have to go to the index and can go straight to the document in memory or on disk.
Howdy, thanks for maintaining this by the way, nice work. However, I don't think I explained my issue clearly.
By example;
find({k:"value"}).first({n:1}) uses any index on k including compound k,n, where-as;
find({k:"value"}).first() always table-scans the find operation, ignoring all indexes.
When testing this behaviour, do not use _id in the find, as that index is kind of special (depending on value object type oddly enough).
I think that is the desired behavior. What index would we choose? I think using no index is the appropriate choice. It would be slower to load the first document from an index because of the extra layer of indirection.
If that were true then what good are indexes, ever?
Look at the 2 examples in my previous comment. If you run these on non-trivial datasets the second example is tragically slow. It can be sped up substantially by iterating the results 1 times instead of using first(). How can that possibly be desired behavior?
You have a good point. In my head I was only considering the empty selector case. Sorry you are totally correct.