@CompoundIndexes({
@CompoundIndex(name = "fertilizer_idx",
unique = true,
def = "{'name': 1, 'formula': 1, 'type': 1}")
})
public class Fertilizer extends Element implements Serializable {
//class stuff
}
是否可以创建不区分大小写的索引?现在它正在从 NAME
区分到 NAMe
。保存第二个字段小写(或大写)对我来说是不可能的。
谢谢, 佩德罗
最佳答案
在MongoDB 3.4 版之前,我们无法创建不区分大小写的索引。
在 3.4 版中有 collation
选项,允许用户为 字符串比较 指定语言特定规则,例如字母大小写和重音规则标记。
排序规则选项具有以下语法:
collation: {
locale: <string>,
caseLevel: <boolean>,
caseFirst: <string>,
strength: <int>,
numericOrdering: <boolean>,
alternate: <string>,
maxVariable: <string>,
backwards: <boolean>
}
locale 字段是必填;所有其他字段都是可选的。
要创建不区分大小写的索引,我们需要使用必填字段locale 和strength 字段作为字符串比较级别。 strength
允许值范围 1 - 5。 read more about collation
strength 属性确定在整理或匹配文本时是否考虑重音或大小写
示例:
if strength=1 then role = Role = rôle
if strength=2 then role = Role < rôle
if strength=3 then role < Role < rôle
所以我们需要使用strength=2
来创建索引。喜欢:
db.collectionName.createIndex(
{ name: 1, formula: 1, type: 1 },
{
name: "fertilizer_idx",
collation: {locale: "en", strength: 2},
unique: true
}
)
注意:collation
选项不适用于text 索引。
关于mongodb - Mongo 唯一索引不区分大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33736192/