是否可以指定查询在Mongoid中应使用的索引?

Rya*_*arn 5 ruby mongodb mongoid

当一个索引是另一个索引的子集时,MongoDB似乎使用了低效的查询模式.

class Model
  field :status, :type => Integer
  field :title, :type => String
  field :subtitle, :type => String
  field :rating, :type => Float

  index([
    [:status, Mongo::ASCENDING],
    [:title, Mongo::ASCENDING],
    [:subtitle, Mongo::ASCENDING],
    [:rating, Mongo::DESCENDING]
  ])
  index([
    [:status, Mongo::ASCENDING],
    [:title, Mongo::ASCENDING],
    [:rating, Mongo::DESCENDING]
  ])
end
Run Code Online (Sandbox Code Playgroud)

查询时在第一索引正在使用两者status,title以及subtitle和排序上rating,只是对查询时statustitle分选上rating,即使使用explain()连同hint()在JavaScript控制台指出使用第二索引是快4倍.

我如何告诉Mongoid告诉MongoDB使用第二个索引?

Rya*_*arn 7

您可以将提示等选项传递给Mongo::Collection使用Mongoid::Criterion::Optional.extras

一个例子:

criteria = Model.where(:status => true, :title => 'hello world').desc(:rating)
criteria.extras(:hint => {:status => 1, :title => 1, :rating => -1})
Run Code Online (Sandbox Code Playgroud)

extras接受Mongo :: Collection可以处理的任何内容