Unique Indexes on embedded documents

I have a collection called Organizations, each organization has an embedded array of users. Each user has an id that I would like to be unique. I’ve attempted to set up a unique index on 'organizations.users.id', but I’ve found that that I am still able to create multiple users with the same id.

After doing a bit of googling I’ve found that, while you can set unique indexes on embedded documents, they do not actually enforce uniqueness. I am wondering why this is? Is this a bug?

Thanks!

Hi @Greg_Fitzpatrick-Bel,

Index constraints are applied at the document level, so a unique index currently cannot ensure unique values within a single document (for example, in an embedded array).

Per Unique Constraint Across Separate Documents:

The unique constraint applies to separate documents in the collection. That is, the unique index prevents separate documents from having the same value for the indexed key.

Because the constraint applies to separate documents, for a unique multikey index, a document may have array elements that result in repeating index key values as long as the index key values for that document do not duplicate those of another document.

There is some related discussion and a workaround using document validation in SERVER-1068: unique indexes not enforced within array of single document.

Regards,
Stennie

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.