Mongo唯一索引不区分大小写
@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
之间有所区别.保存第二个字段的小写(或大写)对我来说是不可能的.
Is it possible to create the index case insensitive? Right now it is differentiating from NAME
to NAMe
. Saving a second field lowercase (or uppercase) is not a possibility for me.
谢谢, 佩德罗
MongoDB 3.4版之前的版本,我们无法创建不区分大小写的索引 .
Prior of MongoDB version 3.4 we were unable to create index with case insensitive.
3.4版中的collation
选项允许用户为字符串比较指定特定于语言的规则,例如字母大写和重音符号的规则.
In version 3.4 has collation
option that allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.
排序规则选项具有以下语法:
The collation option has the following syntax:
collation: {
locale: <string>,
caseLevel: <boolean>,
caseFirst: <string>,
strength: <int>,
numericOrdering: <boolean>,
alternate: <string>,
maxVariable: <string>,
backwards: <boolean>
}
其中区域设置字段为强制;所有其他字段均为可选.
where the locale field is mandatory; all other fields are optional.
要创建不区分大小写的索引,我们需要使用必填字段 locale 和 strength 字段来进行字符串比较级别. strength
允许值范围为 1-5 . 了解有关整理的更多信息
To create index with case insensitive we need to use mandatory field locale and strength field for string comparison level. strength
allows value rage 1 - 5. read more about collation
strength属性确定整理或匹配文本时是否考虑重音或大小写
示例:
如果 strength = 1 ,则 role = Role =rôle
如果 strength = 2 ,则 role = Role<罗勒(Rôle)
如果 strength = 3 ,则角色<角色<角色
因此,我们需要使用strength=2
创建索引.像:
So we need to use strength=2
to create index. like:
db.collectionName.createIndex(
{ name: 1, formula: 1, type: 1 },
{
name: "fertilizer_idx",
collation: {locale: "en", strength: 2},
unique: true
}
)
NB :collation
选项不适用于文本索引.
N.B: collation
option is not available for text indexes.