MongoDB中具有两个字段的唯一约束 [英] Unique Constraint with Two Fields in MongoDB

查看:585
本文介绍了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:

  1. 没有记录将电子邮件和friends_email的值相同.所以这将是无效的:

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

    简而言之,emailfriends_email的连接将是唯一的,而nullundefined的连接将合并为空字符串.

    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?

    推荐答案

    您可以在emailfriends_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中应用约束?

    这篇关于MongoDB中具有两个字段的唯一约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆