如何用MongoDB根据其他属性更新对象属性?

6xfqseft  于 2022-12-12  发布在  Go
关注(0)|答案(1)|浏览(160)

I try to update a sport tournament pool table in a MongoDB collection. Pool tables data look that way :

{
        id: 1,
        pool: 'A',
        teams: [
            {name:'New-Zealand', wins: 4, draws: 0, losses: 0, PointsFor: 143, PointsAgainst: 35,  DIFF: 0},
            {name:'France',      wins: 3, draws: 0, losses: 1, PointsFor: 129, PointsAgainst: 41,  DIFF: 0},
            {name:'Italy',       wins: 2, draws: 0, losses: 2, PointsFor: 88,  PointsAgainst: 75,  DIFF: 0},
            {name:'Uruguay',     wins: 0, draws: 1, losses: 3, PointsFor: 50,  PointsAgainst: 102, DIFF: 0},
            {name:'Namibia',     wins: 0, draws: 1, losses: 3, PointsFor: 53,  PointsAgainst: 113, DIFF: 0}
        ]
    },
    {
        id: 2,
        pool: 'B',
        teams: [
            {name:'South-Africa', wins: 3, draws: 1, losses: 0, PointsFor: 132, PointsAgainst: 32,  DIFF: 0},
            {name:'Ireland',      wins: 3, draws: 1, losses: 0, PointsFor: 126, PointsAgainst: 35,  DIFF: 0},
            {name:'Scotland',     wins: 2, draws: 0, losses: 2, PointsFor: 95,  PointsAgainst: 69,  DIFF: 0},
            {name:'Tonga',        wins: 1, draws: 0, losses: 3, PointsFor: 66,  PointsAgainst: 91,  DIFF: 0},
            {name:'Romania',      wins: 0, draws: 0, losses: 4, PointsFor: 30,  PointsAgainst: 110, DIFF: 0}
        ]
    }
];

I have written the functions that increment wins, draws, losses, PointsFor and PointsAgainst according to some forecasts stored in an other collection. Now, I'm trying to change DIFF properties so that for each object in teams array, DIFF = PointsFor - PointsAgainst.
I'm new to MongoDB and I thought about using the '$subtract' method but I don't understand how aggregation operations work. Thanks in advance for your assistance.

shyt4zoc

shyt4zoc1#

您可以通过下面的更新/聚合操作(4.2+)来执行此操作:

db.collection.update({},
[
{
"$addFields": {
  "teams": {
    "$map": {
      "input": "$teams",
      "as": "t",
      "in": {
        "$mergeObjects": [
          "$$t",
          {
            DIFF: {
              "$subtract": [
                "$$t.PointsFor",
                "$$t.PointsAgainst"
              ]
            }
          }
        ]
        }
      }
    }
  }
 }
],
{
 multi: true
})

解释道:
1.使用$addFields/$map/$mergeObjects/$subtract遍历所有teams数组元素并更新DIFF字段。
1.使用{multi:true}更新选项更新您的集合中的所有文档
Playground

相关问题