Unique Constraint with Two Fields in MongoDB

2020-02-24 12:52发布

I have a collection with fields "email" and "friends_email". I would like to setup a unique-ness constraint like the following, using MongoDB:

  1. 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" }
    }
    

    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.

What's the best way to enforce this rule in MongoDB?

标签: mongodb
3条回答
迷人小祖宗
2楼-- · 2020-02-24 13:12

It sounds like you need a compound unique index:

db.users.createIndex( { "email": 1, "friends_email": 1 }, { unique: true } )

... and you can verify at the ORM layer that email =/= friends_email.

查看更多
再贱就再见
3楼-- · 2020-02-24 13:20

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:

How to apply constraints in MongoDB?

查看更多
ゆ 、 Hurt°
4楼-- · 2020-02-24 13:24

for the second case, is a unique compound index what you're looking for?

 db.emails.ensureIndex( {email:1, friends_email:1}, { unique: true } )

As for the first case, I am not sure if there is a way to enforce the first rule. You may need to perform the check on the application side.

查看更多
登录 后发表回答