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

169
Vistas
¿Cómo puedo aplicar agregados en una matriz de objetos?

Tengo estos datos complicados en MongoDB, quiero reconstruirlos en algo así como el segundo JSON, probé tanto el agregado de MongoDB como la extensión de JavaScript, pero no pude resolverlo.

Datos originales

 [ { "_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 } ]

Reconstruir datos

 [ { "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" } ] } ]

¿Y cómo debo lidiar con este tipo de reconstrucción de datos en el front-end o back-end? ¿Cuál es mejor práctica?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Es mejor hacerlo en el backend y recomendado.

Puede lograr esto de varias maneras en el backend utilizando el marco de agregación de mongo. Es un marco muy poderoso con múltiples operadores para manejar este tipo de datos.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Siempre puede crear un transformador personalizado para convertir un JSON en otro JSON y le sugiero que deje que el back-end maneje esta responsabilidad.

A continuación se muestra un ejemplo usando 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));

EDITAR: si desea consultar datos de mongodb, puede usar la siguiente consulta para obtener el resultado

 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