使用MongoDB聚合框架舍入到小数点后2位

编程入门 行业动态 更新时间:2024-10-20 03:36:08
本文介绍了使用MongoDB聚合框架舍入到小数点后2位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用mongodb聚合框架并进行一些计算,如下所示

I am using the mongodb aggregation framework and doing some calculations as shown below

db.RptAgg.aggregate( { $group : { _id : {Region:"$RegionTxt",Mth:"$Month"}, ActSls:{$sum:"$ActSls"}, PlnSls:{$sum:"$PlnSls"} } }, { $project : { ActSls:1, PlnSls:1, ActToPln:{$cond:[{ $ne: ["$PlnSls", 0] },{$multiply:[{$divide: ['$ActSls', '$PlnSls']},100]},0]} } } );

我试图找出最好的和最简单的方法将我的结果四舍五入到小数点后两位.以下是我的结果

I am trying to figure out what is the best and easiest way to round my results to 2 decimal places. Following is my result

{ "result" : [ { "_id" : { "Region" : "East", "Mth" : 201301 }, "ActSls" : 72, "PlnSls" : 102, "ActToPln" : 70.58823529411765 } ], "ok" : 1

}

我希望显示"ActToPln"而不是"ActToPln":70.58823529411765 ,因为它来自聚集框架本身.我想避免在应用程序中进行四舍五入

I want "ActToPln" to show 70.59 instead of "ActToPln" : 70.58823529411765, in the results from aggegation framework itself. I want to avoid doing the rounding in my application

可以帮忙吗?

以下是我使用的数据集.

Following is the dataset i used.

{ "_id" : ObjectId("51d67ef69557c507cb172572"), "RegionTxt" : "East", "Month" : 201301, "Date" : "2013-01-01", "ActSls" : 31, "PlnSls" : 51 } { "_id" : ObjectId("51d67ef69557c507cb172573"), "RegionTxt" : "East", "Month" : 201301, "Date" : "2013-01-02", "ActSls" : 41, "PlnSls" : 51 }

先谢谢了. 南都

推荐答案

没有$round运算符,但是您可以在聚合框架中执行此操作-按特定顺序执行通常可以避免浮点精度问题.

There is no $round operator but you can do this in the aggregation framework - doing it in specific order will usually avoid floating point precision issues.

> db.a.save({x:1.23456789}) > db.a.save({x:9.87654321}) > db.a.aggregate([{$project:{ _id:0, y:{$divide:[ {$subtract:[ {$multiply:['$x',100]}, {$mod:[{$multiply:['$x',100]}, 1]} ]}, 100]} }}]) { "y" : 1.23 } { "y" : 9.87 }

鉴于问题中已有的管道,请替换:

Given the existing pipeline in the problem, replace:

{$multiply:[{$divide: ['$ActSls', '$PlnSls']},100]}

使用

{$divide:[ {$subtract:[ {$multiply:[ {$divide: ['$ActSls','$PlnSls']}, 10000 ]}, {$mod:[ {$multiply:[{$divide: ['$ActSls','$PlnSls']}, 10000 ]}, 1]} ]}, 100 ]}

使用您的样本数据点可以得出以下结果:

With your sample data points this is the result:

{ "ActSls" : 31, "PlnSls" : 51, "ActToPln" : 60.78 } { "ActSls" : 41, "PlnSls" : 51, "ActToPln" : 80.39 } { "ActSls" : 72, "PlnSls" : 102, "ActToPln" : 70.58 }

更多推荐

使用MongoDB聚合框架舍入到小数点后2位

本文发布于:2023-07-06 08:01:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1047619.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:小数点   框架   MongoDB   舍入到

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!