0

Good day!

I have a collection with documents like

{
  account_id: "accountOne"
  state: stateOne
}

I want to make sure that there is only one document that has pair accountID<->state, where state equals to stateOne, but I want to be able to have many documents where state equals to any value different from stateOne

For example I want to be able to have this data in my collection:

{
  account_id: "accountOne"
  state: stateOne
}

{
  account_id: "accountOne"
  state: stateTwo
}

{
  account_id: "accountOne"
  state: stateTwo
}

If I make uniq index like {account_id: 1, state: 1} I will get an error. Is there any way to do it via db ? Or I have to do it via my sevice logic?

3
  • Maybe provide us the command how you created the index. And the most important question: What do you mean by "I will get an error"? Please provide the error you get! Commented Mar 18, 2022 at 10:05
  • If I make uniq index on {account_id: 1, state: 1} fields I could not create several documents with "state: stateTwo" - I will get duplicate key index error on insert Commented Mar 18, 2022 at 10:11
  • What is the criteria that distinguishes stateOne from other states (other than that there can be only one stateOne that is associated with an account_id). Commented Mar 18, 2022 at 11:49

1 Answer 1

1

Try this one:

db.collection.createIndex(
   { account_id: 1, state: 1 },
   { unique: true, partialFilterExpression: { state: stateOne } }
)
Sign up to request clarification or add additional context in comments.

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.