Home > Back-end >  Mongoose - $project nested array of object to root level of array
Mongoose - $project nested array of object to root level of array

Time:09-20

My db schema looks like that:

[
  {
    title: {
      de: "Test",
      en: "test"
    },
    infos: [
      {
        label: {
          de: "Test",
          en: "test"
        },
        data: [
          {
            label: {
              de: "Test",
              en: "test"
            }
          },
          
        ],
        
      }
    ],
    
  }
]

If I use $project in model.aggregate([]) everything is working fine for objects, so it results in:

title: 'Test' when using following projection:

{title: `$title.de`,}

but for arrays of objects, it just merges all objects in an array like that:

    "infos": [
        {
            "label": [
                "Preparation",
                "Important"
            ]
        }
    ]

when using this projection:

'infos.label': `$infos.label.de`

Same for the nested array.

But the result should look like that:

{
 infos: [
  {
    label: 'Test',
    data: [
     {
       label: 'Test'
     },
    ],

  }
 ]
}

Does someone has an idea how to archive something like that?

CodePudding user response:

You should just use $map to iterate over the array and change it accordingly, like so:

db.collection.aggregate([
  {
    $project: {
      title: "$title.de",
      infos: {
        $map: {
          input: "$infos",
          in: {
            $mergeObjects: [
              "$$this",
              {
                label: "$$this.label.de"
              }
            ]
          }
        }
      }
    }
  }
])

Mongo Playground

  • Related