'MongoDB index with specific field value

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?



Solution 1:[1]

Try this one:

db.collection.createIndex(
   { account_id: 1, state: 1 },
   { unique: true, partialFilterExpression: { state: stateOne } }
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wernfried Domscheit