gpt4 book ai didi

mongodb - PyMongo SON 操纵器/转换不工作(mongodb)

转载 作者:可可西里 更新时间:2023-11-01 09:20:44 25 4
gpt4 key购买 nike

在保存到 MongoDB 之前,我正在尝试使用操纵器将小数转换为 float 。数据来自 SQL Server 数据库,我使用基于 freeTDS 的 pymssql 导入。

我已按照 MongoDB 文档中的说明进行操作,但我不断收到错误消息:

File "build\bdist.win32\egg\pymongo\collection.py", line 467, in insert_one
File "build\bdist.win32\egg\pymongo\collection.py", line 430, in _insert
bson.errors.InvalidDocument: Cannot encode object: Decimal('5019.13')

这是我的转换代码:

import decimal
class Transform(SONManipulator):
def transform_incoming(self, son, collection):
for (key, value) in son.items():
if isinstance(value, decimal.Decimal):
son[key] = float(value)
elif isinstance(value, dict):
son[key] = self.transform_incoming(value, collection)
return son

我把它添加到数据库的地方:

def get(collection):
client = MongoClient(uri)
db = client[database]
db.add_son_manipulator(Transform())
return db[collection]

当我打电话时

collection = get('mycollection')
collection.insert_one(object)

最佳答案

根据 MongoDB Changelog ,自 MongoDB 3.0 起,SONManipulator API 已被弃用并且不会在 db.insert_one() 上工作:

The SONManipulator API has limitations as a technique for transforming your data. Instead, it is more flexible and straightforward to transform outgoing documents in your own code before passing them to PyMongo, and transform incoming documents after receiving them from PyMongo.

Thus the add_son_manipulator() method is deprecated. PyMongo 3’s new CRUD API does not apply SON manipulators to documents passed to bulk_write(), insert_one(), insert_many(), update_one(), or update_many(). SON manipulators are not applied to documents returned by the new methods find_one_and_delete(), find_one_and_replace(), and find_one_and_update().

然而,它可以在 db.insert() 上工作,但它也被弃用了。

因此,您最好在应用代码和数据库之间的边界上编写自定义转换器。

关于mongodb - PyMongo SON 操纵器/转换不工作(mongodb),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33289643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com