我有這樣的檔案:
{
"_id": {
"teamName": "BILALATI6449",
"tournamentId": "197831"
},
"players": [
{
"_id": "113069",
"points": 55
},
{
"_id": "249044",
"points": 0
},
{
"_id": "113129",
"points": 0
},
{
"_id": "196713",
"points": 0
},
{
"_id": "181056",
"points": 0
},
{
"_id": "2331078",
"points": 0
},
{
"_id": "7486355",
"points": 0
},
{
"_id": "113036",
"points": 0
},
{
"_id": "249047",
"points": 0
},
{
"_id": "658022",
"points": 0
},
{
"_id": "182623",
"points": 0
}
],
"totalTeamPoints": 0,
"__v": 0
}
每當更新任何點欄位時,我想對玩家陣列內物件中的所有點進行求和,并將此總和放入 totalTeamPoints 中。我怎樣才能做到這一點。我使用貓鼬,但任何形式的幫助表示贊賞。
uj5u.com熱心網友回復:
我認為這可能會有所幫助,還請根據自己的模態名稱更改模態名稱,例如檔案到產品
const results = await Document.aggregate([
{ "$addFields": {
"totalTeamPoints": {
"$sum": "$players.points"
}
} },
]);
uj5u.com熱心網友回復:
按條件更新玩家點數 在這里測驗
db.collection.update({
"_id.teamName": "BILALATI6449"
},
{
$inc: {
"players.$[elem].points": 1
}
},
{
multi: true,
new : true,
arrayFilters: [ { "elem._id": { $eq: "113069" } } ]
})
更新 totalTeamPoints 點數并回傳修改后的檔案 Test Here
db.collection.update({
"_id.teamName": "BILALATI6449"
},
[
{
$set: {
totalTeamPoints: { $sum: "$players.points" }
}
},
],
{
multi: true,
new : true
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/355645.html
上一篇:在mongoosenodejs中使用擴展模式時丟失資料
下一篇:總結貓鼬中的值
