简体   繁体   English

如何舍入mongodb聚合中的值

[英]How to round a value in mongodb aggregation

I have function which calculate min, max and mean of given date range from db collection.我有从 db 集合计算给定日期范围的最小值、最大值和平均值的函数。 I need the min, max and mean but as rounded values.我需要最小值、最大值和平均值,但作为四舍五入的值。

Sample Doc :示例文档:

 {
    maxspeed: 27.264,
    minspeed: 11.5,
    meanspeed: 14.407407407
 }

Code :代码 :

exports.findspeedminmaxmean = (req, res) => {
    var a=req.query.osm_start_node_id;
    var b= req.query.osm_end_node_id;
    var date1=req.query.utc_timestamp;
    var num1=parseInt(a);
    var num2=parseInt(b);
     console.log(a);

    speeddata.aggregate([{ $match: { 'osm_start_node_id': num1,'osm_end_node_id':num2,'utc_timestamp':{$gte:date1[0],$lte:date1[1]}}},
    {$group:{_id:"$osm_start_node_id",_id:"$osm_end_node_id",maxspeed:{$max:"$speed_mph_mean"},
    minspeed:{$min:"$speed_mph_mean"},
    meanspeed:{$avg:"$speed_mph_mean"}}}])
  .then(stable => {
      if(!stable) {
          return res.status(404).send({
              message: "record not found " + req.query.osm_way_id
          });            
      }
      res.send(stable);
      console.log(stable);
  }).catch(err => {
      if(err.kind === 'osm_way_id') {
          return res.status(404).send({
              message: "record not found " + req.query.osm_way_id
          });                
      }
      return res.status(500).send({
          message: "something wrong with name " + req.query.osm_way_id
      });
  });
 };

On MongoDB version >= 4.2 , you can use $round :在 MongoDB 版本 >= 4.2 ,您可以使用$round

db.collection.aggregate([
  {
    $addFields: {
      maxspeed: {
        $round: [
          "$maxspeed",
          0
        ]
      },
      minspeed: {
        $round: [
          "$minspeed",
          0
        ]
      },
      meanspeed: {
        $round: [
          "$meanspeed",
          0
        ]
      }
    }
  }
])

Test : MongoDB-Playground测试: MongoDB-Playground

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM