I am trying to create a partial index on a field, but only when the field is not null. In other words, I want to be able to have many of the documents be able to store null, but for documents that actually have a value in the field, I want that value to be unique. Here is the code I tried to use
db.account.createIndex({ "email": 1 }, { unique: true, partialFilterExpression: { "email": { $ne: null } }})
From what I thought I understood, this should index the email field when it is not equal to null.
But it gives the error:
"unsupported expression in partial index: $not email $eq null"
I tried to change $ne: null to $exists: true, but there are already multiple documents with null value for the email field, so it also threw an error. My schema has an email field for the document, so each document will automatically have an email field, meaning $exists: true won't work anyways.
Any help on being able to index a field only when it is not null would be great.