2

我有一个关于 mongodb 索引的问题。假设我们有两个模型:

class Book
  include Mongoid::Document

  field :user_id
  field :borrower_id

  belongs_to :user
end

class User
  include Mongoid::Document

  has_many :books
end

问题

如果我能找到一些书:

current_user.books.roder_by(:created_at.desc)

我应该为 Book 创建哪个索引

index({user_id: 1, created_at: -1})

或者

index({user_id: 1})
index({created_at: -1)

为什么?

4

1 回答 1

0

I would go for the compound index due to a number of limitations within MongoDBs (new) index intersectioning which means that two indexes cannot be used separately for find and sort of a query: http://docs.mongodb.org/manual/core/index-intersection/#index-intersection-and-sort as such in this case two separate indexes are not optimal for answering your query, only one index will be used, most likel it will be a in-memory sort limited to 32MB of RAM.

It is also good to note that ndex intersectioning is a last resort at all times. You should only do it if you cannot performantly create a compound index to cover the query since intersectioning is very expensive to begin with.

于 2015-01-15T11:52:13.653 回答