Can I create index with specified value?

Hi, I would like to store jobs in a collection with these attributes: state & hash_value.
When the job is first created, state will be pending. I want to allow for 1 job with state pending and unique hash_value at a time.
Lets say there’s hash_value 123 and state pending, if I create a job with hash_value 123 and state pending I want the index error to be triggered.
But if there is only a job with hash_value 123 and state failed in the collection, I want to allow job creation as there is no hash_value 123 and state pending.
I guess I can query the collection first before creation, but I just want to know if this is achievable through unique index. Thanks

Hi @freddie_mercury ,

Yes unique index will restrict duplicate combination of values on the indexed fields.

So indexing { hash_value : 1, status : 1} with unique : true option should solve this.

Thanks
Pavel

No, I mean, I want to allow multiple jobs of hash_value 123 and status: failed. Just that if status is pending, the hash_value must be unique.

You could create a unique:true partial index on hash_value with status:pending as condition.

2 Likes

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