Mongo 数据库如何使用电子邮件作为唯一键? [英] Mongo database how to use email as unique key?
问题描述
我创建了一个 mongodb 集合,并希望将email"字段标记为唯一的,所以我这样做了(这是一个 Java 代码,尽管这里的语言实际上并不重要):
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);
然后我尝试像这样插入 2 个文档:
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 重复键错误集合:wagon.w_users 索引:email_text dup key: { : "com", : 0.6666666666666666 }
E11000 duplicate key error collection: wagon.w_users index: email_text dup key: { : "com", : 0.6666666666666666 }
如果我将 gmail.com 更改为例如gmail.comm,它抛出这个异常
If I change gmail.com to e.g. gmail.comm, it throws this exception
E11000 重复键错误集合:wagon.w_users 索引:email_text复制密钥:{ : "gmail", : 0.66666666666666666 }
E11000 duplicate key error collection: wagon.w_users index: email_text dup key: { : "gmail", : 0.6666666666666666 }
我看到的解决方法是散列用户的电子邮件并创建一个像emailhash"这样的字段,但对我来说它看起来像拐杖.也许我在这里错过了一些重要的设置?我们可以使用电子邮件作为唯一键吗?
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?
推荐答案
错误来自您的索引创建:您正在创建一个 文本索引 使用
The error come from your index creation : you're creating a text index by using
userCollection.createIndex(Indexes.text("email"), indexOptions);
因此 mongodb 围绕@"和."解析您的字符串,并索引提取的单词.由于您的索引使用 'unique' 选项进行了注释,所以您的第二次插入失败.取而代之的是,创建一个简单的升序索引:
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);
这篇关于Mongo 数据库如何使用电子邮件作为唯一键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!