【问题标题】:About mongodb index关于mongodb索引
【发布时间】:2015-01-15 08:21:05
【问题描述】:

我有一个关于 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)

为什么?

【问题讨论】:

  • 复合索引,因为 MongoDB 不能使用索引 intersectionijng 进行排序和查找,因此后两个索引将不适合回答查询。当然,无论如何索引交叉都不是最佳的

标签: mongodb mongoid mongodb-indexes


【解决方案1】:

由于 MongoDB(新)索引交叉中存在许多限制,我会选择复合索引,这意味着两个索引不能单独用于查找和排序查询:http://docs.mongodb.org/manual/core/index-intersection/#index-intersection-and-sort 在这种情况下是两个独立的索引并不是回答您的查询的最佳选择,只会使用一个索引,很可能是内存中的排序,限制为 32MB 的 RAM。

还需要注意的是,ndex 交集始终是最后的手段。仅当您无法高效地创建复合索引来覆盖查询时,您才应该这样做,因为交集一开始就非常昂贵。

【讨论】:

    猜你喜欢
    • 2011-02-18
    • 2016-02-05
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 2013-03-15
    • 2020-06-24
    • 2011-08-21
    • 2021-08-24
    相关资源
    最近更新 更多