I have customer collection with a field hospital id, bvn and phone.
I want to build an index such that if I try to insert a new document and the hospital ids match it should apply a unique constraint to the bvn and phone to ensure the same hospital does not create duplicate data.
example :
doc1 (in db) = {hospital_id: 1, bvn: 1, phone: 1};
if I try to insert a new doc {hospital_id: 1, bvn: 2, phone: 1} or {hospital_id: 1, bvn: 1, phone: 2}; it should flag as duplicate since they have the same hospital_id and therefore the unique attributes have been applied to those fields.
if i try to insert a doc with {hospital_id: 2, bvn: 1, phone: 1}; or {hospital_id: 1, bvn: 2, phone: 2}; it should be successful since the hospital ids are unique or the fields are not duplicated with the same hospital_id as exists on the db.
I tried to do this with compound index but it does not work
hospitalSchema.index({ hospital_id: 1, bvn: 1, phone: 1 }, { key: unique: true });
then with partial index
hospitalSchema.index({ hospital_id: 1, bvn: 1, phone: 1 }, { unique: true, partialFilterExpression: { $eq: this.hospital_id} });
If I understand your question correctly, what you need is a unique combination of bvn and phone per hospital_id. Please let me know if my understanding is correct here.
As per the above assumption, you can create unique compound indexes on hospital_id and bvn and hospital_id and phone.