Unión de dos colecciones JSON con arrays anidados: MongoDB y PostgreSQL

Conoce cómo fusionar dos fuentes JSON con arrays anidados para sumar ventas por fecha, caja y producto usando MongoDB y PostgreSQL JSONB, con ejemplos de pipeline y casos de uso.

18 sept 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

En entornos donde se requieren combinar dos orígenes de datos en formato JSON con arrays anidados, como ventas diarias registradas en cajas que contienen listas de productos, es necesario descomponer, agregar y volver a reensamblar la información por fecha, caja y producto. El reto consiste en sumar las cantidades por producto por caja agrupando los documentos de dos fuentes distintas y devolver la estructura anidada original con los totales acumulados.

Solución en MongoDB: la agregación por etapas facilita el trabajo con documentos JSON. Un flujo típico incluye estas etapas: $unionWith para concatenar ambas colecciones; $unwind para desplegar el array info y luego info.products; $group con $sum para sumar las cantidades por empleado, fecha, caja y producto; un $group posterior que vuelva a agrupar productos por caja usando $push o $push equivalente; y finalmente $project y $sort para dar forma al resultado. Este enfoque es directo para JSON nativo y devuelve documentos con info como un array de cajas y, dentro de cada caja, un array de productos con sus contadores totales.

Solución en PostgreSQL: con JSONB se reproduce la misma lógica mediante expresiones SQL y funciones JSON. Se suele usar WITH para crear etapas tipo pipeline: primero UNION ALL entre ambas tablas, luego CROSS JOIN LATERAL jsonb_array_elements para descomponer info en registros por caja, y otra jsonb_array_elements para extraer productos. Después se agrupa con SUM y GROUP BY para obtener totales por empleado, fecha, caja y producto. Para reensamblar la estructura se usan jsonb_build_object y jsonb_agg para crear arrays de productos y arrays de cajas. En PostgreSQL 17 y posteriores se puede usar JSON_TABLE, JSON_OBJECT y JSON_ARRAYAGG siguiendo el estándar SQL/JSON para una sintaxis más declarativa.

Resumen de mapeo entre operadores: MongoDB $unionWith equivale a UNION ALL; $unwind equivale a CROSS JOIN LATERAL jsonb_array_elements o JSON_TABLE; $group + $sum equivale a GROUP BY con SUM; $group + $push equivale a jsonb_agg o JSON_ARRAYAGG; $project y $sort equivalen a SELECT con ORDER BY. En la práctica, MongoDB ofrece una experiencia muy natural para documentos JSON, mientras que PostgreSQL aporta la robustez y las capacidades relacionales y de consulta avanzada sobre JSONB.

Ventajas prácticas: si trabajas intensamente con documentos JSON y pipelines de agregación, MongoDB permite escribir transformaciones en menos pasos conceptuales. Si tu entorno requiere integridad relacional, transacciones y funciones SQL complejas, PostgreSQL ofrece herramientas potentes para manipular JSONB junto con el resto del modelo relacional.

Ejemplos de uso real: combinar fuentes de ventas diarias para generar informes consolidados, alimentar cuadros de mando en Power BI o sistemas de inteligencia de negocio, y automatizar procesos de consolidación diaria de datos. Si necesitas una solución a medida para integrar y transformar estos datos, en Q2BSTUDIO diseñamos aplicaciones a medida y software a medida que implementan pipelines de datos fiables y escalables. También ofrecemos servicios de inteligencia artificial para empresas, agentes IA y automatizaciones que enriquecen los flujos con análisis predictivo y recomendaciones inteligentes.

Sobre Q2BSTUDIO: somos una empresa de desarrollo de software especializada en aplicaciones a medida, inteligencia artificial aplicada al negocio, ciberseguridad, servicios cloud aws y azure, y soluciones de inteligencia de negocio incluyendo Power BI. Además prestamos servicios de pentesting y auditoría de seguridad, y ayudamos a diseñar arquitecturas modernas que integran datos de bases relacionales y documentales para obtener insights accionables.

Si te interesa consolidar datos JSON anidados entre MongoDB y PostgreSQL, optimizar procesos de ingestión o desplegar dashboards con servicios inteligencia de negocio y power bi, ponte en contacto con nuestro equipo y te propondremos la arquitectura, el pipeline de agregación y la automatización adecuada para tu caso de uso.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat