简体   繁体   English

将集合中的所有MongoDB浮点值四舍五入到小数点后两位

[英]Round all MongoDB float values in a collection to 2 decimal places

Is there a quick and easy way to tell Mongo that for properties that have values that are floats with over 10 decimal places that I do not care about that level of detail and would like all values to be rounded to 2 decimal places? 有没有一种快速简便的方法来告诉Mongo,对于那些浮点数超过10个小数位的属性,我并不关心该细节级别,并且希望将所有值都舍入到2个小数位?

eg, in collection X I have 例如,在收藏X我有

{'a': 13.4823423, 'b': 12.423424524342342}

and many similar documents thousands of times over, and I want 和许多类似的文件成千上万次,我想

{'a': 13.48, 'b': 12.42}

I know this is a failure on my end of inputting the data this way, and in my head the quick fix would be a python script to go over everything and round it, but my question is specifically is there a built in Mongo command that handles cases like this really well? 我知道这是我以这种方式输入数据的最后一次失败,而在我看来,快速解决方案是使用Python脚本遍历所有内容并将其四舍五入,但是我的问题是是否专门有一个内置的Mongo命令来处理这样的情况真的很好吗? . Thanks. 谢谢。

You can use Math.round with Math.pow. 您可以将Math.round与Math.pow一起使用。 For example, you can get 13.48 as 例如,您可以获得13.48作为

Math.round(x['a'] * Math.pow(10,2)) * Math.pow(10, -2) Math.round(x ['a'] * Math.pow(10,2))* Math.pow(10,-2)

Not fancy, but workable. 不花哨,但可行。

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

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