必须创建带collation选项的索引才能实现大小写不敏感查询;mongodb版本须≥3.4,低于此版本不支持collation;创建索引需指定locale和caselevel或strength参数;查询时collation必须与索引定义完全一致,否则索引不生效。

在MongoDB中实现姓名、邮箱或产品名称等字段的大小写不敏感查询时,仅靠普通索引无法保证排序和匹配的一致性;必须显式创建带collation选项的索引,否则find({name: "Alice"})可能无法命中name: "alice"的文档,即使该字段已建索引。
确认MongoDB版本支持Collation
执行 db.version() 查看当前版本,【必须为3.4及以上】。3.2及更早版本不支持collation参数,强行添加会报错“unrecognized field 'collation'”。
若版本低于3.4,请先升级副本集或分片集群的所有节点,否则后续所有操作均无效。
为字符串字段创建大小写不敏感索引
方法一:使用createIndex命令指定locale和caseLevel
db.users.createIndex({ name: 1 }, { collation: { locale: "en", caseLevel: true } })
方法二:简化写法(默认caseLevel为false,需显式设为true才启用大小写忽略)
db.users.createIndex({ email: 1 }, { collation: { locale: "en", strength: 2 } })
【strength: 2 表示忽略大小写但区分重音符号;strength: 1 则连重音也忽略,慎用】。例如法语café和cafe在strength: 1下视为相同,在strength: 2下不同。
验证索引是否生效
第一步:插入两条测试数据
db.users.insertMany([{ name: "Alice" }, { name: "alice" }])
第二步:执行带相同collation的查询
db.users.find({ name: "alice" }).collation({ locale: "en", caseLevel: true })
第三步:查看执行计划
db.users.find({ name: "alice" }).collation({ locale: "en", caseLevel: true }).explain("executionStats")
检查返回结果中的executionStats.nReturned是否为2,且indexName字段显示刚创建的索引名。若显示COLLSCAN,则说明索引未被使用——常见原因是查询时未声明collation,或collation参数与索引定义不完全一致(如locale写成"en_US"而索引用的是"en")。











