Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

232
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda