Cha*_*had 2 indexing mongoose mongodb node.js express
所以我知道索引可以使查询更快,但我不明白如何确定应该和不应该索引的内容。例如我正在看这个
var FavoriteSchema = new Schema({
user: {
type: ObjectId,
ref: 'User',
required: true,
index: true,
},
business: {
type: ObjectId,
ref: 'Business',
required: true,
index: true,
},
isDeleted: {
type: Boolean,
required: false,
default: false,
},Run Code Online (Sandbox Code Playgroud)
我注意到用户和业务有index:true但isDeleted没有,但为什么呢?我还想知道以这种方式建立索引如何加快查询速度?
来自文档:
如果没有索引,MongoDB 必须执行集合扫描,即扫描集合中的每个文档,以选择那些与查询语句匹配的文档。如果查询存在适当的索引,MongoDB 可以使用该索引来限制必须检查的文档数量。
在这里阅读更多内容:
您要在集合中查询具有特定用户 ID 的文档吗?可能是的,所以你应该为此创建索引。
您要查询集合中具有特定isDeleted值的文档吗?如果是,则为其创建索引。如果不是,或者只是有时,则不要创建索引。