我正在研究一项搜索功能,我必须在其中搜索文档中的多个字段。
我有以下案例:
1) 获取所有field1,field2,field3,field4匹配字符串(nayyar)的文档
2) 获取 field1、field2、field3、field4 匹配字符串 (nayyar) 且性别应为(输入值)或 'N/A' 的所有文档。
3) 获取 field1、field2、field3、field4 与字符串 (nayyar) 匹配且年龄应介于 ageHigh 和 ageLow 之间且性别应为(输入值)或“N/A”的所有文档。
4) 获取 field1、field2、field3、field4 与字符串 (nayyar) 匹配且年龄应介于 ageHigh 和 ageLow 之间且性别应为(输入值)或 'N/A' 且 ArrayField in 'atoz' 的所有文档.
var Schema = new Schema({
lowAge : {
type: Number,
default: 0
},
highAge : {
type: Number,
default: 0
},
gender : {
type: String,
default: 'N/A'
},
field1 : {
type: String
},
field2 : {
type: String
},
field3 : {
type: String
},
field4 : {
type: String
},
arrayField : {
type: [String]
}
});
Schema.index({field1:1, field2:1, field3:1, field4:1});
Schema.index({field1:1, field2:1, field3:1, field4:1, arrayField:1,lowAge:1, highAge:1, gender:1,});
索引的方式是否正确?
最佳答案
首先,在字段上创建索引的想法似乎不错。但是,在查询中使用的所有可能字段上创建索引看起来并不正确。
帖子中列出的所有查询都包含这四个字段。如果你对这4个字段都创建一个复合索引,我想应该就足够了。
此外,您正在架构级别定义索引。当应用程序启动时,Mongoose 会自动为模式中的每个已定义索引调用 ensureIndex。这可能会导致一些性能影响。
您需要考虑以下事项:-
1) 单字段索引,即创建四个索引,每个字段一个。
示例:
db.collection.createIndex({field1 : 1});
如果您需要按 field1、field2、field3 或 field4 或一个或多个字段的组合查找文档,请选择此选项。
在这个选项中,索引是独立的。 MongoDB 将始终使用索引(即索引之一)结束。
2) 复合索引即创建一个包含四个字段的索引
示例:
db.collection.createIndex({field1 : 1, field2 : 1, field3 : 1, field4 :1});
如果您始终使用 field1,请选择此选项。
如果在任何情况下都没有 field1,则 MongoDB 不会使用索引。
关于node.js - Mongoose 文档中的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39554575/