何时创建索引,何时不创建索引

When to create an Index and when not to

我正在使用 MongoDB Native 2.0+。 我有一个名为 services 的集合。此集合包含引用另一个集合中 clients 的文档。这意味着,每项服务都是 "owned" 一个客户。

大约有 50-200 个客户。 每个客户端理论上可以 "own" 大约 1-50 个服务,但实际上对于大多数客户端来说可能是 1-10 个左右。

每个服务都有两个字段作为唯一标识符。一个是 _id,它在管理员 URL 中使用,并作为文档之间的不可变引用。另一个是 slug 这是一个更简单的标识符,主要用于 public URL 以提高可读性。

我对这个集合的查询主要有两种:

db.services.find({client: clientID, _id: id}).toArray(callback)
db.services.find({client: clientID, slug: slug}).toArray(callback)

认为我必须创建以下两个复合索引以实现最佳查询:

db.services.ensureIndex({client: 1, _id: 1})
db.services.ensureIndex({client: 1, slug: 1})

但考虑到每个客户可能提供的服务数量很少(?)"owned"。也许只有一个索引就足够了。要么...

db.services.ensureIndex({client: 1})

或者只有这个复合索引

db.services.find({client: clientID, slug: slug}).toArray(callback)

... 因为 slug 查询可能比 `_id 使用得更多。

你会创建什么索引?

感谢您提供有关此的所有提示!

在我看来,_idslug 在服务集合中都是唯一的,所以我不明白如何搜索 client value 将比仅在 _idslug 上单独使用简单索引来提高性能。

当然 _id 会有一个开箱即用的索引,所以我认为您只需要创建 {slug: 1} 索引。