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

219
Visualizações
How to duplicate a document during aggregation in mongo?

Is there any way to duplicate a document during aggregation in mongo? For example, I've got a "Person" schema that looks like that:

Person:

{
  _id: ObjectId,
  fullName: string,
  matches: number
}

I want to make an aggregation that returns all the persons and duplicates each person's document by the number of his matches.

for example for this collection:

[{
  _id: 1,
  fullName: "John Doe",
  matches: 1
},
{
  _id: 2,
  fullName: "Bla Bla",
  matches: 2
}]

The result will be:

[{
  _id: 1,
  fullName: "John Doe",
  matches: 1
},
{
  _id: 2,
  fullName: "Bla Bla",
  matches: 2
},
{
  _id: 2,
  fullName: "Bla Bla",
  matches: 2
}]

I know that I can add fields to the documents during the aggregation but didn't found anything about adding documents.

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

0

  • $map to iterate loop of range, $range start from 0 and end at matches number, it will return array of current root document
  • $unwind deconstruct matches array
  • $replaceRoot replace matches object to root
db.collection.aggregate([
  {
    $project: {
      matches: {
        $map: {
          input: { $range: [0, "$matches"] },
          in: "$$ROOT"
        }
      }
    }
  },
  { $unwind: "$matches" },
  { $replaceRoot: { newRoot: "$matches" } }
])

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