我正在嘗試操作資料集以使其易于在 mongoCharts 中顯示。有兩組team_a 和team_b,每組包含一組playerId、score、rank 和 Prize。我想展開物件內的陣列,還想將兩個陣列合并為一個。
示例檔案:
{
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",
},
]
}
非常感謝任何指導或指示。謝謝
uj5u.com熱心網友回復:
解決方案1
第一$project階段:
team_a場與team_a.playersteam_b場與team_b.playersall_winners帶有$concatArraysforteam_a.players和的欄位team_b.players
第二$project階段:
id從team_a,team_b,all_winners陣列欄位中洗掉欄位。
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
}
}
}
])
示例 Mongo Playground(解決方案 1)
解決方案2
替代,用于$unset洗掉team_a.players.id和team_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"
]
}
}
}
])
示例 Mongo Playground(解決方案 2)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/315788.html
標籤:javascript 数组 MongoDB 目的 聚合框架
上一篇:如何在Java中列印此物件?
