3

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you Tom for your awnser that works perfect for me :) I tried to apply the same logic in the nested array data array ("infos.data"). Unfortunately I get an error back. Could you tell me what a notation for the nested array would look like so that I get the same result for the respective language? ("infos.data.label")
Sure, you just need to keep nesting the same logic, like this.
Hey @TomSlabbaert I have another question about this topic. Do you have an idea why the syntax $project: {title: '$title.en'} is not working for deep population? When I populate and add this projection the "title" is not displayed when I add this projection: $project: {anotherTitle: "$title.en"} the "anotherTitle" is displayed in the result. Do you know if this is the wanted behaviour and do i made a mistace. This syntax is just not working for deep populate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.