MongoDB + Python,意外的数值类型

MongoDB + Python, unexpected numeric types

我有以下 Python 代码:

from pymongo import MongoClient
db = MongoClient("mongodb://localhost/")["admin"]
collection = db["collection_test"]
collection.insert_one({"key1": 1000000000.1, "key2": 1.1})
doc = collection.find_one()
print(type(doc["key1"]))
print(type(doc["key2"]))

打印:

<class 'float'>
<class 'float'>

但基于 docs 我预计类型是

<class 'bson.decimal128.Decimal128'>

后跟类似 'bson.double' 的内容。

为什么我没有看到 BSON Decimal128 和 BSON Doubletype() 不是在此上下文中获取类型的正确方法吗?

Python floats 存储为 BSON doubles。 API 在插入时转换它们并在查询时将它们转换回来。

如果要存储和检索 BSON Decimal128 值,请使用 bson.decimal128.Decimal128()

from bson.decimal128 import Decimal128

db = MongoClient()["mydatabase"]
collection = db["collection_test"]

collection.insert_one({"key1": Decimal128("1000000000.1"), "key2": Decimal128("1.1")})
doc = collection.find_one()
print(type(doc["key1"]))
print(type(doc["key2"]))

打印:

<class 'bson.decimal128.Decimal128'>
<class 'bson.decimal128.Decimal128'>

文档(尽管有些混乱): https://pymongo.readthedocs.io/en/stable/api/bson/index.html

另外:小心使用admin数据库;它是 MongoDB.

中的一个特殊数据库