I have a collection with object structure like so:
{
emails: [{email:"bob@jones.com", type: "work"}],
_companyId: "FLEHFHOIEFHOIHEFHL"
}
I want to create a unique index so that the combination of emails and _companyId is unique. I would just make a simple compound index, but when I save two people without emails, it throws an error on the second, because it has indexed no value for the emails.email field, leaving just the _companyId in the index, which throws a duplicate key error when I try to insert the second without email. I want it only to index the field if there is an email present. So I found the partialFilterExpression capability. Unfortunately, this isn't working! It doesn't throw any errors, but it happly allows duplicates!
People.ensureIndex({ 'emails.email': 1, _companyId: 1 }, {
unique: 1,
partialFilterExpression: {
"emails": { "email": { $and: [{ $exists: true, $ne: "" }] } }
},
collation: { locale: "en", strength: 2 }
});
So I changed it to this:
People._ensureIndex({ 'emails.email': 1, _companyId: 1 }, {
unique: 1,
partialFilterExpression: {
"emails.email": { $and: [{ $exists: true, $ne: "" }] }
},
collation: { locale: "en", strength: 2 }
});
And it won't create the index at all saying:
Error: key emails.email must not contain '.'
Is there a way to do what I am trying to do, or is it a lost cause?
Ok, figured it out:
People.ensureIndex({ 'emails.email': 1, _companyId: 1 }, {
unique: 1,
partialFilterExpression: {
"emails.email": { $exists: true }
},
collation: { locale: "en", strength: 2 }
});
It said that I couldn't use $ne, so I just had to make sure in my code to remove any blank values.