综合平均值

时间:2016-11-07 07:26:13

标签: mongodb mongodb-query aggregation-framework

我希望我在MongoDB聚合中找到的平均值能够得出一个综合值

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

我运行的查询以获得" rateVal"

的平均值
db.calcR.aggregate([
    {
            $group: {
                _id: null,  

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

            }
    }

输出为{ avg: 3.6666 }但理想情况下我希望它显示为4

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

  }
]

2 个答案:

答案 0 :(得分:3)

要对mongoDb中的值进行舍入,您可以使用$ceil$floor

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

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

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

输出看起来像

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

  }
]

答案 1 :(得分:1)

由于文档中不允许在 $group 阶段使用一元运算符累加器(例如:$round),您可以在 $addFields 阶段使用它们。这样,在您的情况下,组阶段定义的 avg 字段将被 $addFields 阶段覆盖:

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