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

288
Vistas
Check for value to be in an array in $cond

Im trying to project a value in my aggregation pipeline based on if any array in an array contaibns a specific value.

This is a simplified version of how the data looks:

[
  {
    "permissions": [
      {
        "owners": [
          "1"
        ]
      }
    ]
  },
  {
    "permissions": [
      {
        "owners": [
          "2",
          "3"
        ]
      }
    ]
  }
]

And Ive tried to do the following (with "2" being the example value I am searching for):

{
    "$project": {
      owner: {
        $cond: {
          if: {
            $in: [
              "2",
              "$permissions.owners"
            ]
          },
          then: true,
          else: false
        }
      }
    }
  }

Playground Example

But it always ends up being false. Any ideas?

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

0

The problem is $permissions.owners is a nested array. Check this example to look that.

So you have to $unwind the array. But, if there is only one array you can look for into first position in the array like this

But, assuming there could be many arrays, you can use this query.

  • $unwind the array to get each value separated.
  • $set the value into owner variable if exists the number 2.
  • $group to get values again.

At this point, exists a variable called owner which is a boolean array. So the next step is similar to the query you have.

  • $set again to know if exists true in any value, so, the variable will be true too.
db.collection.aggregate([
  {
    "$unwind": "$permissions"
  },
  {
    "$set": {
      "owner": {
        "$in": [
          "2",
          "$permissions.owners"
        ]
      }
    }
  },
  {
    "$group": {
      "_id": "$_id",
      "permissions": {
        "$push": "$permissions"
      },
      "owner": {
        "$push": "$owner"
      }
    }
  },
  {
    "$set": {
      "owner": {
        "$in": [
          true,
          "$owner"
        ]
      }
    }
  }
])

Example here

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