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

270
Visualizações
Mongo aggregation: add field derived from another field

I have documents of the following form present in a collection:

{
  name: "Michael",
  likes: [{ name: "reading", amount: 80}, {name: "eating", amount: 70}]
}

I want to add a new field to all the documents which will be 0/1 depending on whether the person likes reading. I have to check for the presence of likes.name = "reading". I tried adding the following stage in my aggregation pipeline to achieve this:

$addFields: {
  likes_reading: {
    $cond: {
      if: {
        $eq: ["$likes.name", "reading"]
      },
      then: 1,
      else: 0
    }
  }
}

However, $eq doesn't seem to be checking if "any" element of likes array has the required name, which is the kind of behaviour I've seen in many other places when we compare values with arrays. As a result all the likes_reading are set to 0. I need help setting this new field properly.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Since likes is an array you have to use $in operator so try this:

{
    $addFields: {
        likes_reading: {
            $cond: {
                if: { $in: ["reading", "$likes.name"] },
                then: 1,
                else: 0
            }
        }
    }
}

Or

{
    $addFields: {
        likes_reading: {
            $cond: [{ $in: ["reading", "$likes.name"] }, 1, 0]
        }
    }
}
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