痛点:由于在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}