Dachstein
Dachstein

Reputation: 4272

MongoDB - unique index over entire Set

Is it possible to create a unique index in MonboDB over an entire Set lets say UserId's?

Example code

@Indexed
val participantIds: Set<UserId>

Such that, the entire Set is unique. This combination only exists once.

Example

[1, 2] // OK
[2, 3] // OK
[2, 1] // NOT OK (combination exists already)

UPDATE

The use case is for a messaging system. The participantIds are the members of that single or group messenger.

After reading the answers, I feel checking it in the e.g. Service Layer might be my use case with a $all / $size query check to verify that such combination does not exist.

Upvotes: 1

Views: 80

Answers (2)

You cannot add a unique index for an array or collection attribute. You must check this constraint in the business logic.

Probably the best solution is adding a previous validation step before trying to persist your data.

Upvotes: 1

Tom Slabbaert
Tom Slabbaert

Reputation: 22276

There is no out of the box solution that Mongodb provides.

You'll have to implement a workaround yourself, what I would do personally would be unique indexing a new field which would contain the set numbers:

const newDoc = { participantIds: [1, 2, 3]};
const uniqueStr = newDoc.participantIds.sort().join('');

await db.collection.insertOne({ ...newDoc, uniqueField: uniqueStr });

Now by building a unique index on uniqueField you could maintain this. Mind you this field will need to be updated on every document update which adds a lot of overhead.

Maybe if you could provide more details as to what you're trying to do and achieve it would be easier to help you come up with a more viable solution.

Upvotes: 1

Related Questions