我有一个字段"email"和"friends_email"的集合.我想使用MongoDB设置如下所示的唯一约束:
没有记录对email和friends_email具有相同的值.所以这将是无效的:
{"email": "abc@example.com", "friends_email": "abc@example.com" }
Run Code Online (Sandbox Code Playgroud)没有2条记录对所有字段都具有相同的值.所以下面的例子都是无效的:
{
{ "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" }
}
Run Code Online (Sandbox Code Playgroud)
用简单的英语来说,它就像是串联的,email并且friends_email将是唯一的,null并且undefined被合并成空字符串.
在MongoDB中强制执行此规则的最佳方法是什么?
Win*_*eld 37
听起来你需要一个复合唯一索引:
db.users.createIndex( { "email": 1, "friends_email": 1 }, { unique: true } )
Run Code Online (Sandbox Code Playgroud)
...并且您可以在ORM层验证email =/= friends_email.
对于第二种情况,您要寻找的是唯一的复合索引吗?
db.emails.ensureIndex( {email:1, friends_email:1}, { unique: true } )
Run Code Online (Sandbox Code Playgroud)
至于第一种情况,我不确定是否有办法强制执行第一条规则。您可能需要在应用程序端执行检查。
你可以有复合唯一索引email,并friends_email确保第二种情况字段。但是对于第一种情况,您需要在应用程序代码中进行处理,或者使用Java映射器(例如Morphia)进行基于字段的验证。您可能还想查看以下帖子:
| 归档时间: |
|
| 查看次数: |
14633 次 |
| 最近记录: |