Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Python class object instance to mongodb BSON string

Does anyone know of a Python library that can convert a class object to a mongodb BSON string? Currently my only solution is to convert the class object to JSON and then JSON to BSON.

like image 815
S-K' Avatar asked Jan 03 '13 13:01

S-K'


People also ask

What is BSON in Python?

BSON (Binary JSON) encoding and decoding. The mapping from Python types to BSON types is as follows: Python Type. BSON Type. Supported Direction.

What is the data structure of MongoDB BSON?

BSON's binary structure encodes type and length information, which allows it to be traversed much more quickly compared to JSON. BSON adds some non-JSON-native data types, like dates and binary data, without which MongoDB would have been missing some valuable support.

What is PyMongo module in Python?

PyMongo is a Python distribution containing tools for working with MongoDB, and is the recommended way to work with MongoDB from Python. This documentation attempts to explain everything you need to know to use PyMongo. Installing / Upgrading. Instructions on how to get the distribution.

What is BSON file?

BSON stands for Binary Javascript Object Notation. It is a binary-encoded serialization of JSON documents. BSON has been extended to add some optional non-JSON-native data types, like dates and binary data.


1 Answers

This would be possible by converting the class instance to dictionary (as described in Python dictionary from an object's fields) and then using bson.BSON.encode on the resulting dict. Note that the value of __dict__ will not contain methods, only attributes. Also note that there may be situations where this approach will not directly work.

If you have classes that need to be stored in MongoDB, you might also want to consider existing ORM solutions instead of coding your own. A list of these can be found at http://api.mongodb.org/python/current/tools.html

Example:

>>> import bson
>>> class Example(object):
...     def __init__(self):
...             self.a = 'a'
...             self.b = 'b'
...     def set_c(self, c):
...             self.c = c
... 
>>> e = Example()
>>> e
<__main__.Example object at 0x7f9448fa9150>
>>> e.__dict__
{'a': 'a', 'b': 'b'}
>>> e.set_c(123)
>>> e.__dict__
{'a': 'a', 'c': 123, 'b': 'b'}
>>> bson.BSON.encode(e.__dict__)
'\x1e\x00\x00\x00\x02a\x00\x02\x00\x00\x00a\x00\x10c\x00{\x00\x00\x00\x02b\x00\x02\x00\x00\x00b\x00\x00'
>>> bson.BSON.encode(e)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/bson/__init__.py", line 566, in encode
    return cls(_dict_to_bson(document, check_keys, uuid_subtype))
TypeError: encoder expected a mapping type but got: <__main__.Example object at         0x7f9448fa9150>
>>> 
like image 111
jhonkola Avatar answered Oct 02 '22 00:10

jhonkola