pymongo beson binary 存储

文章讲述了在Python中处理numpy数据时遇到的问题,即需要将numpy数据转换为MongoDB兼容的类型进行存储,之后再取出转换回numpy类型。为了解决这个效率问题,作者采用了pickle将numpy数据序列化为二进制格式,直接以二进制方式存储在MongoDB中,使用时再进行反序列化,简化了数据转换过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

痛点:由于在python中使用numpy 进行数据操作的时候需要转换成mongo的数据类型,才能进行存储,在使用的时候再取出 转换成numpy的数据类型 作为模型的入参。

这样中间多做了一层转换,而且numpy类型有24种,很难每个都判断做转换。

解决方案:为了不影响模型的入参,我们使用pickle存储成二进制 ,使用的时候进行转换。以二进制的方式存储。

# -*- coding: utf-8 -*-
"""
@contact: lishulong.never@gmail.com
@time: 2019/1/30 下午1:33
"""
import datetime
import pymongo

import numpy as np
import pickle
from bson.binary import Binary

uri = "mongodb://writer:password@1xx.xx.171.xx:27017/gtest"



def __get_client():
    client = pymongo.MongoClient(uri)
    return client


db = __get_client()['gtest']

rs = db.test.save({
    'create_time': datetime.datetime.now(),
    'binary_filed': Binary(pickle.dumps({
        'array': np.asarray([1, 2, 3, 4, 5]),
        'int64': np.int64(12),
        'float': np.float64(12.445)
    }))
})

if rs:
    b = db.test.find_one({'_id':rs})
    print b

    c = b.get('binary_filed')

    d = pickle.loads(c)

    print d


result

 

Connected to pydev debugger (build 172.4343.24)
{u'binary_filed': Binary("(dp0\nS'array'\np1\ncnumpy.core.multiarray\n_reconstruct\np2\n(cnumpy\nndarray\np3\n(I0\ntp4\nS'b'\np5\ntp6\nRp7\n(I1\n(I5\ntp8\ncnumpy\ndtype\np9\n(S'i8'\np10\nI0\nI1\ntp11\nRp12\n(I3\nS'<'\np13\nNNNI-1\nI-1\nI0\ntp14\nbI00\nS'\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x03\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x05\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\np15\ntp16\nbsS'float'\np17\ncnumpy.core.multiarray\nscalar\np18\n(g9\n(S'f8'\np19\nI0\nI1\ntp20\nRp21\n(I3\nS'<'\np22\nNNNI-1\nI-1\nI0\ntp23\nbS'\\xa4p=\\n\\xd7\\xe3(@'\np24\ntp25\nRp26\nsS'int64'\np27\ng18\n(g12\nS'\\x0c\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\np28\ntp29\nRp30\ns.", 0), u'_id': ObjectId('5c51390156c545fabdc77238'), u'create_time': datetime.datetime(2019, 1, 30, 13, 41, 18, 816000)}
{'array': array([1, 2, 3, 4, 5]), 'float': 12.445, 'int64': 12}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值