LoginSignup
1
1

More than 5 years have passed since last update.

MongoDBのEmbedded DocumentsにUnique制限をかけたい

Last updated at Posted at 2014-02-24
[
  {
    "name": "hoge",
    "users": [
      { "email": "..." },
      { "email": "..." },
    ]
  },
  ...
}

こういうデータのCollectionがあったとして、users.emailをユニークにしたいんだけど、MongoDBのUnique Indexはドキュメント毎にユニークかどうかを保証するものなようで、同一ドキュメント内で同じデータがあっても通ってしまう。

つまりusers.emailにUnique Indexを張った場合、これは通らないけど

[
  {
    "name": "hoge",
    "users": [
      { "email": "foo@example.com" }
    ]
  },
  {
    "name": "fuga",
    "users": [
      { "email": "foo@example.com" } // 重複エラーになる
    ]
  }
]

これは通るということ。

{
  "name": "hoge",
  "users": [
    { "email": "foo@example.com" },
    { "email": "foo@example.com" } // 同一ドキュメント内なのでOK!
  ]
}

アプリケーション側でなんとかするか、Collectionを分けるしかないんだろうか。umm...

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1