我正在 MongoDB 中為基于 NestJs 的 Web 應用程式保存資料。
我的 MongoDB 資料看起來像這樣
"gameId": "1a2b3c4d5e"
"rounds": [
{
"matches": [
{
"match_id": "1111abc1111",
"team1": {
"team_id": "team8",
"score": 0
},
"team2": {
"team_id": "team2",
"score": 0
}
},
{
"match_id": "2222abc2222",
"team1": {
"team_id": "team6",
"score": 0
},
"team2": {
"team_id": "team5",
"score": 0
}
},
]
}
]
這里我們有每場比賽的gameId,在每場比賽中,有許多回合和許多比賽。每場比賽都有match_id。如何獲取特定比賽資訊并根據gameId和match_id 對其進行編輯?(注意:我愿意根據match_id更新分數)
我試過這樣的事情
const matchDetails = await this.gameModel.findOne({
gameId: gameId,
rounds: { $elemMatch: { match_id: match_id } },
});
但這不起作用并回傳null。如何正確地做到這一點?
uj5u.com熱心網友回復:
問題是,你申請的elemMatch上rounds陣列,但它應該是rounds.matches。將您的查詢更改為以下內容將解決問題:
const matchDetails = await this.gameModel.findOne({
gameId: gameId,
"rounds.matches": { $elemMatch: { match_id: match_id } },
});
編輯:要僅獲取特定匹配元素,您可以使用$unwindand進行簡單聚合$filter:
db.collection.aggregate([
{
"$match": {
"gameId": gameId,
"rounds.matches": { $elemMatch: { match_id: match_id } }
}
},
{
"$unwind": "$rounds"
},
{
$project: {
match: {
$filter: {
input: "$rounds.matches",
as: "match",
cond: {
$eq: [
"$$match.match_id",
match_id
]
}
}
},
_id: 0
}
}
])
mongoplayground上的示例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/369277.html
