Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

233
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda