0

I have a mongo collection like so:

{
  _id: 'asdasdasd',
  battletag: 'battletag#1290',
  games: [{
    id: "somegameid",
    name: "Starcraft II",
    characters: ['corvid'],
    groups: ['Husky Starcraft']
  }, {
    id: "someothergameid",
    name: "World of Warcraft",
    characters: ['corvid', 'crow', 'crowtoe'],
    groups: ['Warlords of Draenor']
  }]
}

I want to ensure that, for every game in games, the id attribute is unique. Is there a way to ensure uniqueness on values in arrays of objects in mongodb?

corvid
  • 10,733
  • 11
  • 61
  • 130

1 Answers1

0

You should rely on mongoDB built-in _id. Create another collection with all the games, and refer to it using its documents _id in the Games array of your collection. You can still store all data not directly related to the game in the Games array, along with the game _id

Billybobbonnet
  • 3,156
  • 4
  • 23
  • 49
  • True, but more of my concern is trying to insert the same `game._id` twice. That is, you try to update the array to contain Starcraft II twice. – corvid Jun 09 '15 at 15:14
  • You should just move each `games` items elements in a dedicated collection. Each entry will have its own `_id` and you can store them in a simple string array `Games`. You might need to include the original document `_id` in your new collection items as well. – Billybobbonnet Jun 09 '15 at 15:20
  • I thought the idea with mongodb was to _de_normalize and that's a more SQL-like approach? – corvid Jun 09 '15 at 16:29
  • We need someone more experienced than me to answer that. I just advised what seemed to make sense to me, but it could be an SQL-like approach (and moreover not efficient). If someone has an approach fitting better into mongoDB philosophy, I would like to see it. I am definitely not skilled enough to answer meta questions. – Billybobbonnet Jun 09 '15 at 16:40