MongoDB中具有两个字段的唯一约束 [英] Unique Constraint with Two Fields in MongoDB
问题描述
我有一个包含电子邮件"和"friends_email"字段的集合.我想使用MongoDB设置如下的唯一性约束:
I have a collection with fields "email" and "friends_email". I would like to setup a unique-ness constraint like the following, using MongoDB:
-
没有记录将电子邮件和friends_email的值相同.所以这将是无效的:
No record will have the same value for email and friends_email. So this would be invalid:
{"email": "abc@example.com", "friends_email": "abc@example.com" }
没有2条记录的所有字段都具有相同的值.因此,以下示例将全部无效:
No 2 records will have the same values for all fields. So the following examples would ALL be invalid:
{
{ "email": "abc@example.com", "friends_email": "def@example.com" },
{ "email": "abc@example.com", "friends_email": "def@example.com" }
}
{
{ "email": "abc@example.com", "friends_email": null },
{ "email": "abc@example.com", "friends_email": null }
}
{
{ "email": null, "friends_email": "abc@example.com" },
{ "email": null, "friends_email": "abc@example.com" }
}
简而言之,email
和friends_email
的连接将是唯一的,而null
和undefined
的连接将合并为空字符串.
In plain english, it would be something like, the concatenation of email
and friends_email
will be unique, with null
and undefined
being coalesced into empty-string.
在MongoDB中实施此规则的最佳方法是什么?
What's the best way to enforce this rule in MongoDB?
推荐答案
您可以在email
和friends_email
字段上使用复合唯一索引,以确保第二种情况.但是对于第一种情况,您需要在应用程序代码中进行处理,或者使用Java映射器(例如Morphia)进行基于字段的验证.您可能还想查看以下帖子:
You can have compound unique index on email
and friends_email
field for ensuring the second case. But for the first case you need to handle that in the application code or use a java mapper such as Morphia to have a field-based validation. You might wanna check the following post also:
这篇关于MongoDB中具有两个字段的唯一约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!