How to index case-sensitive username in mongo?

I am coding a web service where users can choose a username that should be case insensitive. However, I want to allow them to use the registration version of their username.

What is the best way to verify on insertion that the username does not have a case insensitive duplicate? I currently see two ways to do this:

  • saving both the line version and another version with user-entered code and indexing only the line version
  • stores only the version with the argument entered by the user and the lowercase letter for comparison, which hits the index target, I suppose

Is there a better way?

+8
mongodb
source share
4 answers

Saving the original username and canonical version (lowercase for your application) is reasonable. Just make sure that the canonical field is updated in your model whenever a username is specified, and check for constraint violations using a unique canonical field index.

Another scenario where this solution (source and canonical field) makes sense is articles in which the same title can be reused, but the pool (for the URL) must be unique.

+9
source share

MongoDB 3.4 now includes the ability to create a true case insensitive index. This is done by setting a comparison with force 2.

Probably the easiest way to do this is to set the sort in the database itself. Then all requests inherit this sort 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 by index by index:

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

And use it as follows:

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

For more information: https://jira.mongodb.org/browse/SERVER-90

+3
source share

It seems that mongodb will support case insensitive indexing from version 3.4 (coming soon). See this ticket and the collation documentation.

In the example obtained from the mentioned ticket, we see that using collation with a force of 2 in both createIndex and find performs a case-insensitive search:

 > db.myCollection.createIndex({city: 1}, {collation: {locale: "en", strength: 2}}); > db.myCollection.insert({_id: 1, city: "New York"}); > db.myCollection.insert({_id: 2, city: "new york"}); > db.myCollection.find({city: "new york"}).collation({locale: "en", strength: 2}); { "_id" : 1, "city" : "New York" } { "_id" : 2, "city" : "new york" } 
+1
source share

Indexing has nothing to do with it; indexing is there to speed up the search.

 db.userTable.find( { storedUserName: /^userEnteredUserName$/i } ); 

See https://www.google.co.uk/search?q=mongodb+case+insensitive+search

-one
source share

All Articles