如何不区分大小写地索引mongo中的用户名? [英] how to index a username in mongo with case-insensitively?

查看:70
本文介绍了如何不区分大小写地索引mongo中的用户名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Web服务,用户可以选择一个不区分大小写的唯一用户名.但是,我想允许他们使用区分大小写的用户名.

I am coding a webservice where users can pick a username that has to be case-insensitive unique. However I want to allow them to use a case-sensitive version of their username.

在插入时检查用户名没有区分大小写的重复项的最佳方法是什么?我目前看到两种方法:

What is the best way to check at insert that the username doesn't have a case-insensitive duplicate? I currently see 2 ways of doing this:

  • 根据用户输入的大小写存储小写版本和其他版本,并仅索引小写版本
  • 仅存储用户输入大小写的版本,并将其小写以进行比较,这违背了我认为的索引的目的

有更好的方法吗?

推荐答案

MongoDB 3.4现在具有创建真正的不区分大小写的索引的功能.通过指定强度为2的排序规则来完成.

MongoDB 3.4 now includes the ability to make a true case-insensitive index. It is made by specifying a collation with a strength of 2.

最简单的方法可能是对数据库本身设置排序规则.然后所有查询都继承该排序规则并将使用它:

Probably the easiest way to do it is to set a collation on the database itself. Then all queries inherit that collation and will use it:

db.createCollection("cities", { collation: { locale: 'en_US', strength: 2 } } )
db.cities.createIndex( { city: 1 } ) // inherits the default collation
db.cities.find({city:"new york"}) //inherits default collation

或者您可以按索引进行索引:

Or you can do it on an index by index basis:

db.myCollection.createIndex({city: 1}, {collation: {locale: "en", strength: 2}});

并像这样使用它:

db.myCollection.find({city: "new york"}).collation({locale: "en", strength: 2});

有关更多信息: https://jira.mongodb.org/browse/SERVER-90

这篇关于如何不区分大小写地索引mongo中的用户名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆