Home > Mobile >  mongodb count unique constraint on 2 fields
mongodb count unique constraint on 2 fields

Time:10-01

On my car mongodb collection I have user_id and default_car fields. One user can have only one default car but can have multiple non-default cars. For instance this value should be valid :

[{user_id:1,default_car:true},{user_id:2,defaut_tool:true},{user_id:2,defaut_tool:false},{user_id:2,defaut_tool:false}]

user with id 1 has only one car but user with id 2 has 3 cars and one of them is the default one. This example should be invalid :

 [{user_id:1,default_car:true},{user_id:2,defaut_tool:true},{user_id:2,defaut_tool:true},{user_id:2,defaut_tool:false}]

What kind of constraint Do I need to define ? I use mongoose on nodejs.

CodePudding user response:

If you are looking to satisfy a uniqueness constraint within MongoDB, then you will want to look into unique indexes.

In your particular situation, it sounds like the uniqueness constraint should be enforced is that each specific user_id cannot have more than one default_car. Therefore you your index should also be a partial index. Specifically the index should probably resemble the following:

db.<collectionName>.createIndex({_user_id:1},{unique:true, partialFilterExpression:{default_car:true}})
  • Related