Home > Enterprise >  How to sum some fields from document and put this sum in another field
How to sum some fields from document and put this sum in another field

Time:11-09

I have documents like this:

{
  "_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
}

I want to sum all the points in objects inside players array whenever any points field get updated and put this sum in totalTeamPoints. How can I achieve this. I am using mongoose, but any kind of help is appreciated.

CodePudding user response:

I think it could be helpful, and also please the change the Modal name according to own Modal Name, like Document to Product

const results = await Document.aggregate([
        { "$addFields": {
            "totalTeamPoints": {
                "$sum": "$players.points"
            }
        } },
    ]);

CodePudding user response:

Update players points by condition Test Here

db.collection.update({
  "_id.teamName": "BILALATI6449"
},
{
  $inc: {
    "players.$[elem].points": 1
  }
},
{
  multi: true,
  new : true,
  arrayFilters: [ { "elem._id": { $eq: "113069" } } ]
})

Update totalTeamPoints points and return modified document Test Here

db.collection.update({
  "_id.teamName": "BILALATI6449"
},
[
  {
    $set: {
      totalTeamPoints: { $sum: "$players.points" }
    }
  },
],
{
  multi: true,
  new : true 
})
  • Related