codeMayfair
codeMayfair

Reputation: 71

Roundup average value

I want my average which is found in the MongoDB aggregation to come up with a roundup value

 [
      {
        "_id": "581c3d9c55421c16ecaf0b26",
        "uDept": "CoE Design & Research",
        "uName": "Saurabh Raman",
        "rateVal": 3,
        "timeStamp": "11/4/2016 13:17",
        "__v": 0
      },
      {
        "_id": "581c437ea3d9f6087ce3b21e",
        "uDept": "CoE Design & Research",
        "uName": "Sachin P Singh",
        "rateVal": 4,
        "timeStamp": "11/4/2016 13:42",
        "__v": 0
      },
      {
        "_id": "581c6d74a3d9f6087ce3b21f",
        "uDept": "Training",
        "uName": "Rahul Shakya",
        "rateVal": 4,
        "timeStamp": "11/4/2016 16:35",
        "__v": 0
      }
    ]

The query which I run to obtain the average of "rateVal"

db.calcR.aggregate([
    {
            $group: {
                _id: null,  

                avg: {$avg: '$rateVal'},

            }
    }

The output is { avg: 3.6666 } but ideally I want it to appear as 4

[
  {
    "_id": null,
    "avg": 3.6666666666666665,

  }
]

Upvotes: 5

Views: 5328

Answers (2)

kokuta
kokuta

Reputation: 41

Since by documentation unary operator accumulators(eg: $round) are not allowed at $group stage, you can use them at $addFields stage. This way, in your case, the avg field defined at group stage will be overwritten by $addFields stage:

   $addFields: {
    avg: { $round: ['$avg', -1] },
  },

Upvotes: 4

azhar
azhar

Reputation: 1747

To round the value in mongoDb you can use either $ceil or $floor

db.calcR.aggregate([
    {
            $group: {
                _id: null,  

                avg: {$avg: '$rateVal'},

            },
           $project:{
               _id: '$_id' ,
               roundedAvg : { $ceil: '$avg' }
           }
    }]

Output look like

[
  {
    "_id": null,
    "roundedAvg": 4,

  }
]

Upvotes: 7

Related Questions