MongoDB -如何展开数组对象



我试图操纵一个数据集,使其易于在mongoCharts中显示。有两组team_a和team_b,每组包含一组playerId、分数、排名和奖品。我想在对象中展开数组,并将两个数组合并为一个。

示例文档:

{
team_a: {
team_score: 94,
team_name: "team_1",
players: [
{
id: "604f00d43776e45a448628f9",
username: "test_1",
score: "33",
rank: "1",
prize: 15.4,
},
{
id: "60058dd9b88cc1a1e40f2f54",
username: "test_2",
score: "31",
rank: "2",
prize: 15.4,
},
{
id: "60058dd9b88cc1a1e40f2f55",
username: "test_3",
score: "30",
rank: "3",
prize: 15.4,
}
],
},
team_b: {
team_score: 62,
team_name: "team_2",
players: [
{
id: "602ce34a39c7496600940774",
username: "test_4",
score: "32",
rank: "1",
},
{
id: "60058db6b88cc1a1e40f2f4f",
username: "test_5",
score: "30",
rank: "2",
},
],
},
}

期望输出为:

{
team_a: [
{
username: "test_1",
score: "33",
rank: "1",
prize: 15.4,
},
{
username: "test_2",
score: "31",
rank: "2",
prize: 15.4,
},
{
username: "test_3",
score: "30",
rank: "3",
prize: 15.4,
}
],
team_b: [
{
username: "test_4",
score: "32",
rank: "1",
},
{
username: "test_5",
score: "30",
rank: "2",
},
],
all_winners: [
{
username: "test_1",
score: "33",
rank: "1",
prize: 15.4,
},
{
username: "test_2",
score: "31",
rank: "2",
prize: 15.4,
},
{
username: "test_3",
score: "30",
rank: "3",
prize: 15.4,
}
{
username: "test_4",
score: "31",
rank: "4",
},
{
username: "test_5",
score: "30",
rank: "5",
},
]
}

任何指导或指针都非常感谢。谢谢。

解决方案1$project阶段1:

  1. team_afield withteam_a.players
  2. team_b字段与team_b.players
  3. all_winnersfield with$concatArraysforteam_a.playersandteam_b.players

第二$project阶段:

  • team_a,team_b,all_winners数组字段中删除id字段
db.collection.aggregate([
{
$project: {
"team_a": "$team_a.players",
"team_b": "$team_b.players",
"all_winners": {
"$concatArrays": [
"$team_a.players",
"$team_b.players"
]
}
}
},
{
$project: {
"all_winners": {
id: 0
},
"team_a": {
id: 0
},
"team_b": {
id: 0
}
}
}
])

Sample Mongo Playground (Solution 1)


解决方案2

可选,使用$unset删除team_a.players.idteam_b.players.id作为第一阶段。

db.collection.aggregate([
{
$unset: [
"team_a.players.id",
"team_b.players.id"
]
},
{
$project: {
"team_a": "$team_a.players",
"team_b": "$team_b.players",
"all_winners": {
"$concatArrays": [
"$team_a.players",
"$team_b.players"
]
}
}
}
])

Sample Mongo Playground (Solution 2)

相关内容

  • 没有找到相关文章

最新更新