我在玩新的mongodb数据类型NumberDecimal
。一般来说,我开发的科学应用程序需要精确(或尽可能精确),所以我想知道如何使用它。在
我正在开发的应用程序之一是python flask应用程序,它从数据库中提取数据并执行各种计算。但是,当我从mongodb中提取一个NumberDecimal
(假设是NumberDecimal('24.55')
)并尝试将其添加到我在python中创建的bson.decimal128.Decimal128
编号中时,我得到以下错误:
TypeError: unsupported operand type(s) for +: 'Decimal128' and 'Decimal128'
如果我试图将NumberDecimal
转换为decimal.Decimal
(或其他任何东西):
所以我想我有几个问题:(1)有没有办法把这个NumberDecimal
转换成我在python中可以使用的任何东西,(2)如果没有,有没有一种数据类型可以转换成与NumberDecimal
兼容的数据类型,(3)如果没有,在我看来,我可以使用它的唯一方法是使用聚合框架的服务器端(是否还有其他用例)?在
似乎需要将Decimal128实例强制转换为标准Python Decimal128实例才能操作它们。但是您应该在
create_decimal128_context
从bson.decimal128
创建的上下文中执行此操作,以确保以后可以将结果存储在数据库中。在而且,正如您在上面最后两个命令中看到的,要转换为Python的Decimal类型,请使用Decimal128.to_decimal方法。不要尝试在Decimal128构造函数中传递Decimal128实例。在
在python3.6和pymongo3.4上进行了测试。在
灵感来源于pymongo的documentation模块。在
相关问题 更多 >
编程相关推荐