Muhammad Ahsan
Muhammad Ahsan

Reputation: 21

How to round a value in mongodb aggregation

I have function which calculate min, max and mean of given date range from db collection. 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
      });
  });
 };

Upvotes: 2

Views: 2301

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17915

On MongoDB version >=4.2, you can use $round :

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

Test : MongoDB-Playground

Upvotes: 3

Related Questions