Home > front end >  How to update an object property with MongoDB according to others properties?
How to update an object property with MongoDB according to others properties?

Time:12-10

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.

CodePudding user response:

You can do it via below update/aggregation operation (4.2 ):

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

Explained:

  1. Use $addFields/$map/$mergeObjects/$subtract to walk over all teams array elements and update the DIFF field.
  2. Use {multi:true} update option to update all documents in your collection

Playground

  • Related