Home > Blockchain >  MongoDB average of several fields in a new field in a document
MongoDB average of several fields in a new field in a document

Time:02-18

Here is my document in MongoDB:

enter image description here

The Overall field is empty as you can see. What I'm trying to do is the overall field automatically gets Defence Shoot Pass Dribble and Speed fields and calculate the average value of them and put it there.

CodePudding user response:

If you want to modify the value in the DB you can do an update with aggregation like this:

db.collection.update({
  // the document you want to update
  // or empty to update all
  },
  [
    {
      "$set": {
        "Overall": {
          "$avg": [
            "$Defence",
            "$Shoot",
            "$Pass",
            "$Dribble",
            "$Speed"
          ]
        }
      }
    }
  ])

Example here

Also if you only want to get the value when you do a query over the DB (and not modify the DB field) you can use $project in an aggregate stage like this:

db.collection.aggregate([
  {
    "$match": {
      // if needed
      
    }
  },
  {
    "$project": {
      "Overall": {
        "$avg": [
          "$Defence",
          "$Shoot",
          "$Pass",
          "$Dribble",
          "$Speed"
        ]
      }
    }
  }
])

Example here which returns something like this:

[
  {
    "Overall": 7.4,
    "_id": ObjectId("...")
  }
]
  • Related