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

231
Visualizações
How do a merge multiple fields into a single array in an aggregation?

I have data that has user primary keys in "user.pk", and "usertags.user.pk".

[
  {
    _id: ObjectId("62015250cb18d3cadb32c38e"),
    user: { pk: '7485070525' },
    usertags: [ { user: { pk: '334777488' } } ]
  },
  {
    _id: ObjectId("62015250cb18d3cadb32c38f"),
    user: { pk: '334777488' },
    usertags: [
      { user: { pk: '7485070525' } },
      { user: { pk: '271738610' } },
      { user: { pk: '31961021' } }
    ]
  }
]

I am looking to aggregate all this data into a single list of all distinct user primary keys, so the result for the data above would be something like { _id: null, user_pks: [7485070525, 334777488, 271738610, 31961021] }

I tried using the $group aggregation, but I can't figure out how to merge "user.pk", and "usertags.user.pk". Can anyone help me with that?

Edit: This is the closest I've gotten, which puts users and usertags in separate lists.

db.collection.aggregate([
  { $unwind: "$usertags" },
  { $group: { _id: null, users: { $push: "$user.pk" }, usertags: {$push: "$usertags.user.pk" } } },
])
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

you can do this:

test it here mongodb playground

db.collection.aggregate([
  {
    $group: {
      _id: null,
      user_pk: {
        $push: "$user.pk"
      },
      user_sub_pk: {
        $push: "$usertags"
      }
    },
    
  },
  // flattern array in user_sub_pk
  {
    $set: {
      user_sub_pk: {
        $reduce: {
          input: "$user_sub_pk",
          initialValue: [],
          in: {
            $concatArrays: [
              "$$value",
              "$$this"
            ],
            
          },
          
        },
        
      },
      
    },
    
  },
  {
    $project: {
      user_pks: {
        $concatArrays: [
          "$user_pk",
          "$user_sub_pk.user.pk"
        ],
        
      },
      
    },
    // remove duplicate items
    {
    "$project": {
      "user_pks": {
        "$setUnion": [
          "$user_pks",
          []
        ]
      }
    }
  }
    
  }
])

update: refactored by @zrbecker

db.collection.aggregate([
  {
    $group: {
      _id: null,
      users: {
        $push: "$user.pk"
      },
      usertags: {
        $push: "$usertags.user.pk"
      }
    }
  },
  {
    $project: {
      users: {
        $setUnion: [
          "$users",
          {
            $reduce: {
              input: "$usertags",
              initialValue: [],
              in: {
                $concatArrays: [
                  "$$value",
                  "$$this"
                ]
              }
            }
          }
        ]
      }
    }
  }
])
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