0

I have the following structure in my Mongo document:

{ 
  property1: 'value',
  property2: 'value',
  items: [
    {
        name: 'name1'
    },
    {
        name: 'name2'
    },
  ]
}

Is possible to define a local index over the items array? In my case, item.name was a unique key but only in this document. Other documents can have also a item with the same name that a item in other document (but the name in a document cannot be repeated).

Now I'm checking manually if the name is already in use before add/update elements in the document.items array, but if Mongo is capable to do it I will prefer...

EDIT: I have tried to create a index over items.name but if I create that index Mongo doesn't allows to insert/update a item if the name is already defined in other document.

The Matrix
  • 1,268
  • 2
  • 14
  • 23
  • Unique index only works at the document level. If you want mongodb to do this for you then create a separate collection and create indices over there. – Ashh Jul 22 '19 at 13:55
  • Appreciate your fast reply, but note than items are not only a array of values but a structured array. I have read about "$addtoset" before, but I think "$addtoset" is not supporting structured arrays. Please, can you remove the "duplicate" flag due to isn't a duplicated question? – The Matrix Jul 22 '19 at 13:59
  • 1
    Please check the second [Can you specify a key for $addToSet in Mongo?](https://stackoverflow.com/questions/14527980/can-you-specify-a-key-for-addtoset-in-mongo). It will show you how `$addToSet` works with **array of objects**. – Ashh Jul 22 '19 at 14:05

0 Answers0