Search code examples
mongodbmongooseunique-index

How to create a mongo unique index based on fields and a particular value of a field?


I have a bookings collection where I store data like this:

{
_id,
fieldId: (a reference to _id from another collection),
status: a string which can be `valid` or `cancelled` or `completed`,
date: eg. `2022-02-09T13:00:00.000+00:00`
}

Now, I want to ensure that there can be only one booking for a fieldId at a given date that has status: valid. There can be more or none cancelled or completed ones, but the combination between fieldId, date and the value valid of status must be unique. I know how to create an unique index for fieldId and date:

BookingSchema.index({ fieldId: 1, date: 1 }, { unique: true }); 

Is it possible to also add the value valid of status field? If not, should i just check on every booking if there already exists a valid booking for that date and field?


Solution

  • Thank you prasad_ for offering the solution, which is Partial indexes. Here is the solution in mongoose if anybody has the same type of problem:

    BookingSchema.index(
      { fieldId: 1, date: 1 },
      {
        unique: true,
        partialFilterExpression: {
          status: { $eq: `valid` },
        },
      }
    );