问题
I creted a mongodb collection and wanted to mark "email" field as unique in it, so I did this (it's a Java code though language isn't actually important here):
IndexOptions indexOptions = new IndexOptions();
indexOptions.unique(true);
userCollection.createIndex(Indexes.text("email"), indexOptions);
Then I try to insert 2 documents like so:
Document doc = new Document();
doc.append("email", "johnny@gmail.com");
doc.append("username", "John");
doc.append("lastname", "Doe");
userCollection.insertOne(document);
Document doc = new Document();
doc.append("email", "duck@gmail.com");
doc.append("username", "Donald");
doc.append("lastname", "Duck");
userCollection.insertOne(document);
The first one inserts without any problems, the second one throws this exception:
E11000 duplicate key error collection: wagon.w_users index: email_text dup key: { : "com", : 0.6666666666666666 }
If I change gmail.com to e.g. gmail.comm, it throws this exception
E11000 duplicate key error collection: wagon.w_users index: email_text dup key: { : "gmail", : 0.6666666666666666 }
The workaround I see is to hash user's email and create a field like "emailhash" but it looks like a crutch to me. Maybe I'm missing some important setting here? Can we use email as unique key at all?
回答1:
The error come from your index creation : you're creating a text index by using
userCollection.createIndex(Indexes.text("email"), indexOptions);
So mongodb parse your string around '@' and '.', and indexes extracted words. As your index is annotated with 'unique' option, your second insert fails. Instead of that, create a simple ascending index :
userCollection.createIndex(Indexes.ascending("email"), indexOptions);
来源:https://stackoverflow.com/questions/52442590/mongo-database-how-to-use-email-as-unique-key