Daniel Lopez
Daniel Lopez

Reputation: 498

MongoDB $project embedded document to root level with other fields in another document

i have this structure

 {
        "_id": "5e7229c248797243544a15b6",
        "itinerary": [
            {
                "_id": "5e96f905c694d020bc99c2e4"
            },
            {
                "_id": "5e7230360bab9640f82a0e79"
            }
        ]
    },

and need transform document of this way

    { "_id": "5e7229c248797243544a15b6"},
    { "_id": "5e96f905c694d020bc99c2e4"},
    { "_id": "5e7230360bab9640f82a0e79"}

thanks for your help team. :)

Upvotes: 2

Views: 105

Answers (1)

Valijon
Valijon

Reputation: 13113

Try this one:

db.collection.aggregate([
  {
    $project: {
      data: {
        $concatArrays: [
          [
            { _id: "$_id" }
          ],
          {
            $map: {
              input: "$itinerary",
              in: "$$this"
            }
          }
        ]
      }
    }
  },
  {
    $unwind: "$data"
  },
  {
    $replaceRoot: {
      newRoot: "$data"
    }
  }
])

MongoPlayground

Upvotes: 2

Related Questions