1

I have a database structured like this:

            {
                "teams" : [
                    {
                        "best_players" : [
                            {
                                "contact" : {
                                    "name" : "SomeName1"
                                }, 
                                "characteristic" : {
                                    "skills" : "good"
                                 }
                                }
                        ], 
                        "teamname" : "SomeTeam1"
                    }, 
                    {
                    "best_players" : [
                        {
                            "contact" : {
                                "name" : "SomeName2"
                            }, 
                            "characteristic" : {
                                "skills" : "bad"
                             }
                            }
                    ], 
                    "teamname" : "SomeTeam2"
                } 
                    ]
              }

I need to rename arrays and fields, and see the information in a different form. What i'm expecting with aggregation-framework:

{
"team_players" : [
{
"player_name" : "SomeName1",
"player_skills" : "good" ,
"team_name" : "SomeTeam1"
},
{
"player_name" : "SomeName2",
"player_skills" : "bad" ,
"team_name" : "SomeTeam2"
}
]
}

What is the right way to query my result?

3
  • 1
    what should happen when best_players array has more than one player ? Commented Aug 1, 2018 at 15:48
  • It always has one field, but in the structure it is specified as an array Commented Aug 1, 2018 at 15:53
  • share your code Commented Aug 1, 2018 at 15:55

1 Answer 1

1

You can use $map within $project to format documents.

Something like

db.colname.aggregate(
{"$project":{
  "team_players":{
    "$map":{
      "input":"$teams",
      "in":{
        "$let":{
          "vars":{"best_player":{"$arrayElemAt":["$$this.best_players",0]}},
          "in":{
            "player_name":"$$best_player.contact.name",
            "player_skills":"$$best_player.characteristic.skills",
            "team_name":"$$this.teamname"
          }
        }
      }
    }
  }
}})
Sign up to request clarification or add additional context in comments.

4 Comments

I have 1 more quastion, what should i do when best_player array has more than one player?)
what do you want to do ? do you want to get all the players under best players array ?
I mean that in one element in teams array can be more than one player
Sorry. I don't follow you. do you mind creating a new question with sample documents, code that you have tried and expected response ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.