1

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The set of participantIds rarely updates, but it might be. It's for a messenger. 1:1 messaging and group messaging. The participantIds are the members of the group. You gave some valuable input e.g. sorting and creating a hash. However, I think @Eduardo also made a valid point, checking it in the service layer.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.