How to flatten data of mongodb when it's array of nested object and populated

"nbfc_report": [
        {
            "buyer": [
                {
                    "buyer_id": {
                        "_id": "62a8548c21d5976aea2f1787",
                        "company_name": "HERO MOTOCORP LIMITED"
                    },
                    "seller_id": {
                        "_id": "62a8548c21d5976aea2f1787",
                        "company_name": "HERO MOTOCORP LIMITED"
                    },
                    "_id": "62ba95ac8e30735c9a505ed3",
                    "created_at": "2022-06-28T05:46:20.738Z",
                    "updated_at": "2022-06-28T05:46:20.739Z"
                }
            ]
        },

now i have to show only company_name in buyer_id and company_name in seller_id

please help me at least show some example

Hello @Kashif_Iqbal ,

I notice you haven’t had a response to this topic yet - were you able to find a solution?
Based on the sample document provided, you can use this to get company names from your documents.

db.test.aggregate([

// expand the nbfc_report array
{
  $unwind: '$nbfc_report'
}, 

// expand the buyer array
{
  $unwind: '$nbfc_report.buyer'
},

// project the company names
{
  $project:
  {
    buyer_company:'$nbfc_report.buyer.buyer_id.company_name', 
    seller_company:'$nbfc_report.buyer.seller_id.company_name'
  }
}
])

By using above query, you output will look like

  {
    "_id": {
      "$oid": "62fdbb8fe845928ded2de1f8"
    },
    "buyer_company": "HERO MOTOCORP LIMITED",
    "seller_company": "HERO MOTOCORP LIMITED"
  }

Is this the output you’re looking for? If not, could you provide more details:

  • Sample Output
  • Complete sample document
  • MongoDB version

For more details on the stages I used in the example above, please see:

Regards,
Tarun

3 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.