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

354
Visualizações
MongoDB - how to use $project with $cond in aggregate pipeline

my collection has structure like this:

"listQuestion": [
        {
            "answer_type": 0,
            "listShortAnswer": [],
            "listQuestionChildren": [],
            "quiz_type": 1,
            "listPairing": [],
            "listAnswer": [
                {
                    "is_true": false,
                    "answer_content": " \\[x=-2\\] ",
                    "answer_url_image": "",
                    "answer_url_mp3": "",
                    "answer_id": 136948
                },
                {
                    "is_true": true,
                    "answer_content": " \\[x=-1\\] ",
                    "answer_url_image": "",
                    "answer_url_mp3": "",
                    "answer_id": 136950
                },

I have an aggregation variable called $$isShowAnswer, if it is true, the is_true will be show, or else it won't

here is my projection with $cond

$project: {
    'listAnswer.is_true': {
        $cond: { if: { $eq: ["$$isShowAnswer", false] }, then: "$$REMOVE", else: 1}
    },
},

but the result is like below

                {
                    "answer_content": " \\[x=-2\\] ",
                    "answer_url_image": "",
                    "answer_url_mp3": "",
                    "answer_id": 136948,
                    "is_true": 1
                },
                {
                    "answer_content": " \\[x=-1\\] ",
                    "answer_url_image": "",
                    "answer_url_mp3": "",
                    "answer_id": 136950,
                    "is_true": 1
                },

how can I remove "is_true" field if the condition is correct and do nothing if it's wrong?

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

0

In order to update an array you need to use $map. Removing a key by condition is not simple, you can use workaround with $objectToArray and then revert again with $arrayToObject

db.getCollection("collection").aggregate([
   {
      $project: {
         listAnswer: {
            $map: {
               input: "$listAnswer",
               as: 'answer',
               in: {
                  $cond: {
                     if: { $eq: ["$$isShowAnswer", false] },
                     then: { $mergeObjects: ["$$answer", { is_true: 1 }] },
                     else: {
                        $arrayToObject: {
                           $filter: {
                              input: { $objectToArray: "$$answer" },
                              as: 'item',
                              cond: { $ne: ["$$item.k", 'is_true'] }
                           }
                        }
                     }
                  }
               }
            }
         }
      }
   }
])

Another solution would be

  1. {$unwind: "$listAnswer"}
  2. then your { $cond: { if: { $eq: ["$$isShowAnswer", false] }, then: "$$REMOVE", else: 1} }
  3. revert with $group
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