我有从数据库集合计算给定日期范围的最小值,最大值和平均值的函数。我需要最小值,最大值和平均值,但需要四舍五入。
样本文件:
{
maxspeed: 27.264,
minspeed: 11.5,
meanspeed: 14.407407407
}
代码:
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
});
});
};
在MongoDB版本> =上4.2
,可以使用$ round:
db.collection.aggregate([
{
$addFields: {
maxspeed: {
$round: [
"$maxspeed",
0
]
},
minspeed: {
$round: [
"$minspeed",
0
]
},
meanspeed: {
$round: [
"$meanspeed",
0
]
}
}
}
])
测试: MongoDB-操场
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句