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

79
Visualizações
Mongo merge into array

I have the following:

 {_id: blah, anotherId: "externalId", description: "foo"},
 {_id: blah, anotherId: "externalId", description: "bar"},
 ...

I want:

{_id: blah, anotherId: "externalId", descriptions: ["foo", "bar"]}

I know I can simply write this but it's very slow as I have millions of records.

db.collectionOfAnotherId.find().forEach(function(r){ 
    var x = {anotherId: r.id, descriptions: []};
    db.myCollection.find({anotherId: x.anotherId}).forEach(function(d){
         x.descriptions.push(d.description); }); 
         db.newCollection.save(x); 
     })

Any ideas?

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

0

You could use the aggregation framework for this. For example, consider using the $lookup operator to do a left join to myCollection and writing the results of the following $group pipeline to the new collection using $push to create the descriptions array as:

db.collectionOfAnotherId.aggregate([
    {
        "$lookup": {
            "from": "myCollection",
            "localField": "id",
            "foreignField": "anotherId",
            "as": "d"
        }
    },
    { "$unwind": "$d" },
    {
        "$group": {
            "_id": "$_id",
            "anotherId": { "$first": "$id" },
            "descriptions": { "$push": "$d.description" }
        }
    },
    { "$out": "newCollection" }
])
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