Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

240
Views
Unique partialFilterExpression Index on array of objects not working

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!