Merging nested documents

I have this nested document below:
{ "_id": 393657177,
"data": [ { "_id": 2021, "payout": 2938.83633 },
{ "_id": 2022, "payout": 3680.71977 },
{ "_id": 2019, "payout": 3091.98733 },
{ "_id": 2020, "payout": 3184.78084 } ]
}`

But I want to combine it into
{ "_id": 393657177, "year": 2019, "payout": 3091.98733 },
{ "_id": 393657177, "year": 2020, "payout": 3184.78084 },
{ "_id": 393657177, "year": 2021, "payout": 2938.83633 },
{ "_id": 393657177, "year": 2022, "payout": 3680.71977 }

How do I do that?Preformatted text

Hi Willy_Hermanto, welcome to the community.

Please try the aggregate method provided by the mongodb to get the result. Have a look at the aggregate docs for aggregate pipeline stages and aggregate pipeline operators.

db.collection.aggregate([
  {
    $unwind: "$data"
  },
  {
    $sort: {
      "data._id": 1
    }
  },
  {
    $project: {
      "_id": 1,
      "year": "$data._id",
      "payout": "$data.payout"
    }
  }
])

Output:

[
  {
    "_id": "393657177",
    "payout": 3091.98733,
    "year": 2019
  },
  {
    "_id": "393657177",
    "payout": 3184.78084,
    "year": 2020
  },
  {
    "_id": "393657177",
    "payout": 2938.83633,
    "year": 2021
  },
  {
    "_id": "393657177",
    "payout": 3680.71977,
    "year": 2022
  }
]

Hoping it is useful!!
Regards