2013-02-04 14 views
9

私はフィールド "email"と "friends_email"を持つコレクションを持っています。私はMongoDBの使用して、セットアップに次のようなユニークネス制約を希望:MongoDBの2つのフィールドを持つユニークな制約

  1. ませレコードは、電子メールやfriends_emailに対して同じ値を持ちません。これは無効です:

    {"email": "[email protected]", "friends_email": "[email protected]" } 
    
  2. 2つのレコードはすべてのフィールドで同じ値を持ちます。したがって、次の例では、すべての無効次のようになります。平易な英語で

    { 
        { "email": "[email protected]", "friends_email": "[email protected]" }, 
        { "email": "[email protected]", "friends_email": "[email protected]" } 
    } 
    { 
        { "email": "[email protected]", "friends_email": null }, 
        { "email": "[email protected]", "friends_email": null } 
    } 
    { 
        { "email": null, "friends_email": "[email protected]" }, 
        { "email": null, "friends_email': "[email protected]" } 
    } 
    

    、それが何かのようになり、emailfriends_emailの連結がnullundefinedが空の文字列に合体された状態で、ユニークになります。

このルールをMongoDBで実行するには、どのような方法が最適ですか?

答えて

23

あなたは化合物一意のインデックス必要があるようですね:

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

を...そしてあなたはORM層で確認することができます。また、次のポストをチェックしたいかもしれませんそのメールは/ = friends_emailです。

+2

db.collection.ensureIndex(keys、options)はバージョン3.0.0から廃止予定です。> db.collection.ensureIndex()はdb.collection.createIndex()のエイリアスになりました。 –

3

emailfriends_emailフィールドに複合ユニークインデックスを設定して、2番目のケースを確保することができます。しかし、最初の場合は、アプリケーションコードでそれを処理するか、MorphiaなどのJavaマッパーを使用してフィールドベースの検証を行う必要があります。

How to apply constraints in MongoDB?

3

第2のケースでは、あなたが探しているユニークな複合インデックスですか?

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

最初のケースでは、最初のルールを強制する方法があるかどうかはわかりません。アプリケーション側のチェックが必要な場合があります。

関連する問題