我有一个这样的数据库:
{
"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"
}
]
}
使用聚合框架查询结果的正确方法是什么?
答案 0 :(得分:1)
这很好用
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"
}
}
}
}
])
答案 1 :(得分:0)
您可以将$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"
}
}}
]}
}
}
}});