Saving numpy array in mongodb

后端 未结 5 1745
醉话见心
醉话见心 2020-12-23 12:01

I have a couple of MongoDB documents wherein one my the fields is best represented as a matrix (numpy array). I would like to save this document to MongoDB, how do I do this

5条回答
  •  一生所求
    2020-12-23 12:47

    The code pymongo.binary.Binary(...) didnt work for me, may be we need to use bson as @tcaswell suggested.

    Anyway here is one solution for multi-dimensional numpy array

    >>from bson.binary import Binary
    >>import pickle
    # convert numpy array to Binary, store record in mongodb
    >>record['feature2'] = Binary(pickle.dumps(npArray, protocol=2), subtype=128 )
    # get record from mongodb, convert Binary to numpy array
    >> npArray = pickle.loads(record['feature2'])
    

    Having said that, the credit goes to MongoWrapper used the code written by them.

提交回复
热议问题