有没有一种方法可以将python对象直接存储在mongoDB中而无需序列化它们 [英] Is there a way to store python objects directly in mongoDB without serializing them

查看:196
本文介绍了有没有一种方法可以将python对象直接存储在mongoDB中而无需序列化它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过某个地方,您可以使用BSON将python对象(更具体地说是字典)存储为MongoDB中的二进制文件.但是,现在我找不到任何与此相关的文档.

I have read somewhere that you can store python objects (more specifically dictionaries) as binaries in MongoDB by using BSON. However right now I cannot find any any documentation related to this.

有谁知道该怎么做?

推荐答案

无法在不序列化对象的情况下将其存储在文件(数据库)中.如果数据需要从一个进程转移到另一个进程或另一个服务器,则需要以某种形式进行序列化以进行传输.由于您正在询问MongoDB,因此数据绝对会以某种形式进行序列化以便存储在MongoDB数据库中.使用MongoDB时,它是 BSON .

There isn't a way to store an object in a file (database) without serializing it. If the data needs to move from one process to another process or to another server, it will need to be serialized in some form to be transmitted. Since you're asking about MongoDB, the data will absolutely be serialized in some form in order to be stored in the MongoDB database. When using MongoDB, it's BSON.

如果您实际上是在询问是否有一种方法可以在MongoDB文档中存储更原始形式的Python对象,则可以在文档中插入一个Binary字段,该字段可以包含您想要的任何数据喜欢.不能以这种形式直接查询,因此您可能失去了使用NoSQL文档数据库(如MongoDB)的许多好处.

If you're actually asking about whether there would be a way to store a more raw form of a Python object in a MongoDB document, you can insert a Binary field into a document which can contain any data you'd like. It's not directly queryable in any way in that form, so you're potentially loosing a lot of the benefits of using a NoSQL document database like MongoDB.

>>> from pymongo import MongoClient
>>> client = MongoClient('localhost', 27017)
>>> db = client['test-database']
>>> coll = db.test_collection    
>>> # the collection is ready now 
>>> from bson.binary import Binary
>>> import pickle
>>> # create a sample object
>>> myObj = {}
>>> myObj['demo'] = 'Some demo data'
>>> # convert it to the raw bytes
>>> thebytes = pickle.dumps(myObj)
>>> coll.insert({'bin-data': Binary(thebytes)})

这篇关于有没有一种方法可以将python对象直接存储在mongoDB中而无需序列化它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆