-
Type: Task
-
Resolution: Done
-
Priority: Major - P3
-
Affects Version/s: None
-
Component/s: None
-
None
My setup:
class ImportQueue include Mongoid::Document include Mongoid::Timestamps include Mongoid::Attributes::Dynamic field :attrs, :type => Hash # attrs to import index({ :attrs => "hashed" }, { :background => true }) validates :attrs, :presence => true, :uniqueness => true end
The problem is in that the uniqueness validator issues the next query:
find({ attrs: { k: 'v' }).sort({ _id: 1 })
Explain shows the next:
{ "cursor" : "BtreeCursor _id_", "isMultiKey" : false, "n" : 1, "nscannedObjects" : 175164, "nscanned" : 175164, "nscannedObjectsAllPlans" : 350328, "nscannedAllPlans" : 350328, "scanAndOrder" : false, "indexOnly" : false, "nYields" : 116, "nChunkSkips" : 0, "millis" : 1225, "indexBounds" : { "_id" : [ [ { "$minElement" : 1 }, { "$maxElement" : 1 } ] ] }, "server" : "...:27017" }
So the index on attrs is not used. But if we change the query to:
find({ attrs: { k: 'v' }).sort({ _id: 1 })._addSpecial( "$hint", { attrs: 'hashed' } )
Explain shows:
{ "cursor" : "BtreeCursor attrs_hashed", "isMultiKey" : false, "n" : 1, "nscannedObjects" : 1, "nscanned" : 1, "nscannedObjectsAllPlans" : 1, "nscannedAllPlans" : 1, "scanAndOrder" : true, "indexOnly" : false, "nYields" : 0, "nChunkSkips" : 0, "millis" : 0, "indexBounds" : { "attrs" : [ [ NumberLong("5173886864922833935"), NumberLong("5173886864922833935") ] ] }, "server" : "...:27017" }
I do not want to say this is a bug, just an observation. I think that could be solved by a custom validation. But perhaps there is something we can do with this, like if a field has an index and we validating uniqueness on that field the hint could be added automatically.