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

189
Visualizações
MongoDB conditional if else if with exists

I am stuck in a query, my case is

if user id exists then user id
else if user name exists then user name
else if user email exists then user email
else ''

Here, is my code.

$project: {
    ..... other fields,
    'userDetail': {
        $cond: {
            if: {
                $exists: ['$user.id']
            },
            then: '$user.id',
            else: {
                $cond: {
                    if: {
                        $exists: ['$user.name']
                    },
                    then: '$user.name',
                    else: {
                        $cond: {
                            if: {
                                $exists: ['$user.email']
                            },
                            then: '$user.email',
                            else: '',
                        }
                    },
                }
            }
        }
    }
}

Since, $exists don't work on this. Can anybody, help me finding the solution to this problem? Also, if user.id is '' (empty string) & user.name is "Marcus". I want the result to return user.name.

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

0

Query

  • if id is false or empty string, try the name, else if name false or empty string, try the email, else ""
  • false are all not-exists/null/false
  • the types of those fields are not booleans, so you are safe to use this way

*in case you really needed the $exist for example you wanted to keep the null or the false values, you could use this {"$eq":[{"$type":"$user.id"}, "missing"]}

Test code here

aggregate(
[{"$set":
  {"userInfo":
   {"$switch":
    {"branches":
     [{"case":{"$and":["$user.id", {"$ne":["$user.id", ""]}]},
       "then":"$user.id"},
      {"case":{"$and":["$user.name", {"$ne":["$user.name", ""]}]},
       "then":"$user.name"},
      {"case":{"$and":["$user.email", {"$ne":["$user.email", ""]}]},
       "then":"$user.email"}],
     "default":""}}}}])
over 4 years ago · Santiago Trujillo Relatório

0

If I've understood correctly (and based on your example) you can use a query like this:

The trick here is to use ifNull instead of $exists.

db.collection.aggregate([
  {
    "$project": {
      "userDetail": {
        "$cond": [
          {
            "$ifNull": [
              "$user.id",
              false
            ]
          },
          // user id exists
          "$user.id",
          // user id no exists
          {
            "$cond": [
              {
                "$ifNull": [
                  "$user.name",
                  false
                ]
              },
              // user name exists
              "$user.name",
              // user name no exists
              {
                "$cond": [
                  {
                    "$ifNull": [
                      "$user.email",
                      false
                    ]
                  },
                  // user email exists
                  "$user.email",
                  // user email no exists
                  ""
                ]
              }
            ]
          }
        ]
      }
    }
  }
])

Example here

over 4 years ago · Santiago Trujillo Relatório

0

You can use the nested $ifNull operator, by checking nested condition,

  {
    $project: {
      userDetail: {
        $ifNull: [
          "$user.id",
          {
            $ifNull: [
              "$user.name",
              { $ifNull: ["$user.email", ""] }
            ]
          }
        ]
      }
    }
  }

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