Articles in this section
Category / Section

How to flatten nested JSON elements in a MongoDB collection

Published:

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

  1. Create the MongoDB data source.

  2. Drag and Drop the table in the data source designer page.

  3. Switch to Code View mode using the toggle button

    code veiw.png

  4. 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]'
    )
    
  5. Replace the Required columns and table name from Code view mode

  6. 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.

  1. Create the MongoDB data source.
  2. Drag and Drop the table in the data source designer page.
  3. Click the expression button.
    1.png
  4. Now add the query with the required columns.
    jsonb_array_elements([Json data]::jsonb->'[Json field]')->>'[Required field]'
    
  5. Replace the Required columns and JSON field name.
  6. 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.

image.png

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.

Additional References

Was this article useful?
Like
Dislike
Help us improve this page
Please provide feedback or comments
SM
Written by Siranjeevi Murugan
Updated
Comments (0)
Please  to leave a comment
Access denied
Access denied