我有一个结构如下的数据库:
{
"teams" : [
{
"best_players" : [
{
"contact" : {
"name" : "SomeName1"
},
"characteristic" : {
"skills" : "good"
}
},
{
"contact" : {
"name" : "SomeName2"
},
"characteristic" : {
"skills" : "good"
}
}
],
"teamname" : "SomeTeam1"
},
{
"best_players" : [
{
"contact" : {
"name" : "SomeName3"
},
"characteristic" : {
"skills" : "bad"
}
}
],
"teamname" : "SomeTeam2"
}
]
}我需要重命名数组和字段,并以不同的形式查看信息。我对聚合框架的期望是:
{
"team_players" : [
{
"player_name" : "SomeName1",
"player_skills" : "good" ,
"team_name" : "SomeTeam1"
},
{
"player_name" : "SomeName2",
"player_skills" : "good" ,
"team_name" : "SomeTeam1"
},
{
"player_name" : "SomeName3",
"player_skills" : "bad" ,
"team_name" : "SomeTeam2"
}
]
}用aggregation-framework查询结果的正确方式是什么?
发布于 2018-08-02 21:12:02
您可以结合使用$reduce和$concatArrays来转换所有的best_players。
就像这样
db.colname.aggregate(
{"$project":{
"team_players":{
"$reduce":{
"input":"$teams",
"initialValue":[],
"in":{"$concatArrays":[
"$$value",
{"$map":{
"input":"$$this.best_players",
"as":"bp",
"in":{
"player_name":"$$bp.contact.name",
"player_skills":"$$bp.characteristic.skills",
"team_name":"$$this.teamname"
}
}}
]}
}
}
}});发布于 2018-08-02 21:18:26
这个运行得很好。
db.are.aggregate([
{ "$unwind": "$teams" },
{ "$unwind": "$teams.best_players" },
{
"$group": {
"_id": null, "team_players": {
"$push":
{
"player_name": "$teams.best_players.contact.name",
"player_skills": "$teams.best_players.characteristic.skills",
"team_name": "$teams.teamname"
}
}
}
}
])https://stackoverflow.com/questions/51654338
复制相似问题