Vladimir Loct
Vladimir Loct

Reputation: 35

Aggregate the arrays in MongoDB

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?

Upvotes: 1

Views: 46

Answers (1)

s7vr
s7vr

Reputation: 75984

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"
          }
        }
      }
    }
  }
}})

Upvotes: 1

Related Questions