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

标签 mongodb python-2.7

在保存到 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/

相关文章:

java - Querydsl 与 MongoDB 的使用

java - 在一个应用程序中哪个应该是单例? MongoClient 或 MongoDatabase 或 MongoCollection?

node.js - 尝试将 Node js 与 mongoDB Atlas 云连接时出现 UnhandledPromiseRejectionWarning 错误

python - Scrapy - 如何转换输出中的 unicode?

python-3.x - CURL 到 Python 请求的转换 Elasticsearch

node.js - 更新mongodb中的大量文档

mongodb - mongodb 使用 mongoose 进行文本搜索

python - BeautifulSoup : Remove Tags that only contain href

Python:保留列表中项目的第一次出现

google-app-engine - Google App Engine 上的 SSL 证书