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

497
Vistas
Using $exists in MongoDB $cond

For background, I have to create a field in a collection, but ONLY if another known field (an array) is not empty. I'm trying to make a boolean filter with the $and and some conditions:

$set: {
  clientsAllowed: {
            $cond: {
              if: {
                $and: [
                  {
                    businessAllowed: { $exists: true },
                  },
                  {
                    businessAllowed: { $type: "array" },
                  },
                  {
                    businessAllowed: { $ne: [] },
                  },
                ],
              },
              then: [...],
              else: [...],
            },
          }
}

But I get this error:

Invalid $set :: caused by :: Unrecognized expression '$exists'

Is the $exists wrongly formatted? Or is the $and stage? Any ideas?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Type cond for businessAllowed is enough. You don't need to check exists or not.

db.collection.aggregate([
  {
    $set: {
      clientsAllowed: {
        $cond: {
          if: {
            $and: [
              {
                "$eq": [
                  {
                    $type: "$businessAllowed"
                  },
                  "array"
                ]
              },
              {
                $ne: [
                  "$businessAllowed",
                  []
                ]
              }
            ]
          },
          then: [],
          else: []
        }
      }
    }
  }
])

mongoplayground

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