Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

161
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda