MongoDB中两个字段的唯一约束

the*_*her 20 mongodb

我有一个字段"email"和"friends_email"的集合.我想使用MongoDB设置如下所示的唯一约束:

  1. 没有记录对email和friends_email具有相同的值.所以这将是无效的:

    {"email": "abc@example.com", "friends_email": "abc@example.com" }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 没有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.collection.ensureIndex(keys,options)自版本3.0.0起不推荐使用:> db.collection.ensureIndex()现在是db.collection.createIndex()的别名. (2认同)

Kay*_*Kay 7

对于第二种情况,您要寻找的是唯一的复合索引吗?

 db.emails.ensureIndex( {email:1, friends_email:1}, { unique: true } )
Run Code Online (Sandbox Code Playgroud)

至于第一种情况,我不确定是否有办法强制执行第一条规则。您可能需要在应用程序端执行检查。


cub*_*buk 5

你可以有复合唯一索引email,并friends_email确保第二种情况字段。但是对于第一种情况,您需要在应用程序代码中进行处理,或者使用Java映射器(例如Morphia)进行基于字段的验证。您可能还想查看以下帖子:

如何在MongoDB中应用约束?