我有一个这样的数据库:
{
"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"
}
]
}
查询结果的正确方法是什么?
答案 0 :(得分:1)
类似
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"
}
}
}
}
}
}})