How to flatten nested JSON elements in a MongoDB collection
Flattening nested JSON elements in a MongoDB collection can be achieved using code view and expressions. This article will guide you through the process of flattening nested JSON elements using SQL Server and PostgreSQL queries.
{"employees":[
{"name":"ClientA", "email":"test@gmail.com"},
{"name":"ClientB", "email":"test2@gmail.com"},
{"name":"ClientC", "email":"test3@gmail.com"}
]}
Steps to Read JSON Data From MongoDB
For SQL Server
-
Create the MongoDB data source.
-
Drag and Drop the table in the data source designer page.
-
Switch to Code View mode using the toggle button
-
Now added the query with the required columns
SELECT [Required field] FROM OPENJSON((SELECT [Json data] FROM [Table]), '$.[Json field]') WITH ( [Required Field] NVARCHAR(255) '$.[Required field]' )
-
Replace the Required columns and table name from Code view mode
-
Now click the save button to save the changes
By following these steps, you can successfully flatten nested JSON elements in a MongoDB collection using MSSQL database queries.
For PostgreSQL
For the PostgreSQL database, You can achieve the same using expressions.
- Create the MongoDB data source.
- Drag and Drop the table in the data source designer page.
- Click the expression button.
- Now add the query with the required columns.
jsonb_array_elements([Json data]::jsonb->'[Json field]')->>'[Required field]'
- Replace the Required columns and JSON field name.
- Save the expression and save the data source.
By following these steps, you can successfully flatten nested JSON elements in a MongoDB collection using PostgreSQL database queries.
We can use the Bold ETL as a workaround to flatten the MongoDB JSON data from version 7.2 or above. The Array JSON will be formed as a separate table. We can join those tables to get the data together. Please find the help document to Flattening MongoDB Objects in Bold BI Using Bold ETL.