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

162
Visualizações
How can I apply aggregate on array of objects?

I have this complicated data in MongoDB, I want to reconstruct it into something like the second JSON, I tried both MongoDB aggregate and javascript spread, but I couldn't figure it out.

Original Data

[
  {
    "_id": "61ff24b2db73094dd3029c7e",
    "TeamName": "GoodTeam",
    "TeamImage": "Avatar",
    "TeamMember": [
      {
        "name": "Aimee",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "test2@gmail.com",
        "timezone": "PST",
        "_id": "61ff25fcd2a0b9e13ee8989c"
      },
      {
        "name": "Kai",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "school021195@gmail.com",
        "timezone": "PST",
        "_id": "61ff3114d3d343bd673f5ad3"
      },
      {
        "name": "Iren",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "test1@gmail.com",
        "timezone": "AKST",
        "_id": "61ff3114d3d343bd673f5ad4"
      }
    ],
    "createdAt": "2022-02-06T01:30:26.893Z",
    "updatedAt": "2022-02-06T02:23:16.660Z",
    "__v": 0
  }
]

Reconstruct Data

[
  { 
    "timezone":"PST",
    "TeamMember":[
       {
        "name": "Aimee",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "test2@gmail.com",
        "timezone": "PST",
        "_id": "61ff25fcd2a0b9e13ee8989c"
      },
      {
        "name": "Kai",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "school021195@gmail.com",
        "timezone": "PST",
        "_id": "61ff3114d3d343bd673f5ad3"
      },
  {
    "timezone":"AKST",
    "TeamMember":[
      {
        "name": "Iren",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "test1@gmail.com",
        "timezone": "AKST",
        "_id": "61ff3114d3d343bd673f5ad4"
      }
    ]
  }
]

And how should I deal with this kind of data reconstruction in the front-end or back-end? Which one is better practice?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

It is better to do it in the backend and recommended.

You can achieve this by multiple ways in the backend using mongo aggregation framework. It is very powerful framework with multiple operators to handle these kind of data.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can always create a custom transformer for converting one JSON to another JSON and I would suggest you to let the back-end handle this responsibility.

Below is one example using Javascript.

const firstJson = `[
    {
      "_id": "61ff24b2db73094dd3029c7e",
      "TeamName": "GoodTeam",
      "TeamImage": "Avatar",
      "TeamMember": [
        {
          "name": "Aimee",
          "image": "https://i.imgur.com/HeIi0wU.png",
          "email": "test2@gmail.com",
          "timezone": "PST",
          "_id": "61ff25fcd2a0b9e13ee8989c"
        },
        {
          "name": "Kai",
          "image": "https://i.imgur.com/HeIi0wU.png",
          "email": "school021195@gmail.com",
          "timezone": "PST",
          "_id": "61ff3114d3d343bd673f5ad3"
        },
        {
          "name": "Iren",
          "image": "https://i.imgur.com/HeIi0wU.png",
          "email": "test1@gmail.com",
          "timezone": "AKST",
          "_id": "61ff3114d3d343bd673f5ad4"
        }
      ],
      "createdAt": "2022-02-06T01:30:26.893Z",
      "updatedAt": "2022-02-06T02:23:16.660Z",
      "__v": 0
    }
  ]`;

  const firstJsonObj = JSON.parse(firstJson);
  
  const map = new Map();
  for(let i =0;i<firstJsonObj.length;i++){
    for(let j =0;j<firstJsonObj[i].TeamMember.length;j++){
        let timezone = firstJsonObj[i].TeamMember[j].timezone;
        if(map.has(timezone)){
            const team = map.get(timezone);
            team.push(firstJsonObj[i].TeamMember[j]);
            map.set(timezone,team);
        }
        else{
            map.set(timezone,[firstJsonObj[i].TeamMember[j]])
        }
    }
  }

  const secondJson = Array.from(map,function(element){
      const [key,value] = element;
   return {
        timezone : key,
        TeamMember : value
    }
  });
  console.log(JSON.stringify(secondJson));

EDIT: If you want query data from mongodb itself you can use below query to get the output

 db.collection.aggregate([
  {
    "$unwind": "$TeamMember"
  },
  {
    "$group": {
      "_id": {
        "timezone": "$TeamMember.timezone"
      },
      "TeamMember": {
        "$push": "$$ROOT.TeamMember"
      }
    }
  },
  {
    "$project": {
      "_id": 0,
      "timezone": "$_id.timezone",
      "TeamMember": 1
    }
  }
])
about 4 years ago · Juan Pablo Isaza 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