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

275
Vistas
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 Respuestas
Responde la pregunta

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