聚合MongoDB中的阵列

时间:2018-08-01 15:43:00

标签: mongodb nosql mongodb-query aggregation-framework

我有一个这样的数据库:

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

我需要重命名数组和字段,并以其他形式查看信息。 我对聚合框架的期望:

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

查询结果的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以在$map中使用$project来格式化文档。

类似

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