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

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

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 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