Unique Constraint with Two Fields in MongoDB

后端 未结 3 946
庸人自扰
庸人自扰 2020-12-29 04:32

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

相关标签:
3条回答
  • 2020-12-29 05:05

    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.

    0 讨论(0)
  • 2020-12-29 05:18

    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.

    0 讨论(0)
  • 2020-12-29 05:19

    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?

    0 讨论(0)
提交回复
热议问题