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

209
Vistas
Use array field in $cond

Im trying to set a value in my aggregation pipeline based on if any object in an array has a specific value set to true.

            {
                $set: {
                    "read": {$cond: {if: {"permissions.publicRead": true}, then: true, else: false}},
                    "write": false,
                    "owner": false
                }
            }

But its complaining about not allowing a "." in the field name. The data looks something like this:

{
    "permissions": [
        {"publicRead": true},
        {"publicRead": false}
    ]
}

Edit: I also tried using $permissions.publicRead and {if: "permissions.publicRead", then: true, else: false}

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

0

Reason of error: $cond requires to check condition in $eq operator and need to pass $ before $permissions.publicRead in condition,

$cond: { 
  if: { $eq: ["$permissions.publicRead", true] }, then: true, else: false 
}

After resolving above problem the query will work without error but it will not return right result because, the permissions.publicRead will always return array of boolean values,

$eq: ["$permissions.publicRead", true]

is equal to

$eq: [[true, false], true] or $eq: [[false, true], true]

so

[true, false] or [false, true] is not equal to true


Try $anyElementTrue operator to check is array have any true value or not,

db.collection.aggregate([
  {
    $set: {
      "read": {
        $anyElementTrue: "$permissions.publicRead"
      },
      "write": false,
      "owner": false
    }
  }
])

Playground

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