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

204
Visualizações
Add new field to each array elements in Mongodb aggregation based on match condition

I have the following mongodb collection

 {  "id" : "yzes547",
    "courseId" : "aw4a34y7",
    "objectives" : [ 
        {
            "type" : "LESSON",
            "id" : "dfhxytd"
        }, 
        {
            "type" : "MODULE",
            "id" : "rgzeerp"
        }
    ]
}

I want to add new fields for ids of each type in objectives parameter.

Desired output

{  "id" : "yzes547",
    "courseId" : "aw4a34y7",
    "objectives" : [ 
        {
            "type" : "LESSON",
            "id" : "dfhxytd"
        }, 
        {
            "type" : "MODULE",
            "id" : "rgzeerp"
        }
    ]
   "lessonId": "dfhxytd",
   "moduleId": "rgzeerp"
}

I have tried the following query but it only returns False.

db.account.aggregate([
{
    '$project': {
        '_id': 0, 
        'questionId': 1, 
        'courseId': 1, 
        'lessonId': {
            '$cond': [
                {
                    '$eq': [
                        '$objectives.type', 'LESSON'
                    ]
                }, '$objectives.id', False
            ]
        }, 
        'moduleId': {
            '$cond': [
                {
                    '$eq': [
                        '$objectives.type', 'MODULE'
                    ]
                }, '$objectives.id', False
            ]
        }

Is it possible to query the database such that we can get new fields of each type in one aggregation method?

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

0

Yes, you can achieve this quite easily using $map and $objectToArray to create the required fields, finally by using $replaceRoot and $mergeObjects you can add these fields to the original structure, like so:

db.collection.aggregate([
  {
    $replaceRoot: {
      newRoot: {
        "$mergeObjects": [
          "$$ROOT",
          {
            "$arrayToObject": {
              $map: {
                input: "$objectives",
                as: "obj",
                in: {
                  k: {
                    $concat: [
                      {
                        "$toLower": "$$obj.type"
                      },
                      "Id"
                    ]
                  },
                  v: "$$obj.id"
                }
              }
            }
          }
        ]
      }
    }
  }
])

Mongo Playground

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