MongoDB NumberDecimal:+ 不支持的操作数类型:“Decimal128”和“Decimal128”

Joh*_*etz 4 python decimal mongodb

我正在研究新的 mongodb 数据类型NumberDecimal。我通常构建需要精确度(或尽可能精确)的科学应用程序,所以我想知道如何使用它。

我正在构建的应用程序之一是一个 python Flask 应用程序,它从数据库中提取数据并执行各种计算。但是,当我NumberDecimal从 mongodb 中提取aNumberDecimal('24.55')并尝试将其添加到bson.decimal128.Decimal128我在 python 中创建的数字时,出现以下错误:

TypeError: unsupported operand type(s) for +: 'Decimal128' and 'Decimal128'
Run Code Online (Sandbox Code Playgroud)

如果我尝试转换NumberDecimaldecimal.Decimal(或其他任何内容):

TypeError: Cannot convert Decimal128('24.55') to Decimal
Run Code Online (Sandbox Code Playgroud)

所以我想我有几个问题:(1)是否可以将其转换NumberDecimal为我可以在 python 中使用的任何内容,(2)如果没有,是否有一种数据类型我可以将所有其他数字转换为与NumberDecimal,( 3)如果没有,在我看来,我可以使用它的唯一方法是使用聚合框架在服务器端(还有其他用例)吗?

Raf*_*afa 8

看来您需要将 Decimal128 实例转换为标准 Python 小数才能操作它们。create_decimal128_context但是您应该在由, from创建的上下文中执行此操作bson.decimal128,以确保结果稍后可以存储在数据库中。

>>> from bson.decimal128 import Decimal128, create_decimal128_context
>>> import decimal
>>>
>>> D128_CTX = create_decimal128_context()
>>>
>>> with decimal.localcontext(D128_CTX):
...     d1 = Decimal128('1.23')
...     d2 = Decimal128('3.21')
...     d3 = Decimal128(d1.to_decimal() + d2.to_decimal())
...
>>> print(d3, type(d3))
4.44 <class 'bson.decimal128.Decimal128'>
>>> print(d3.to_decimal(), type(d3.to_decimal()))
4.44 <class 'decimal.Decimal'>
>>> decimal.Decimal(d3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: conversion from Decimal128 to Decimal is not supported
Run Code Online (Sandbox Code Playgroud)

而且,正如您在上面的最后两个命令中看到的,要转换为 Python 的 Decimal 类型,请使用Decimal128.to_decimal方法。不要尝试在 Decimal 构造函数中传递 Decimal128 实例。

在 Python 3.6 和 pymongo 3.4 上测试。

受到 pymongo模块文档bson.decimal128的启发。