6

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.

S-K'
  • 3,188
  • 8
  • 37
  • 50
  • 1
    Are you looking for [pymonogo](http://api.mongodb.org/python/current/tutorial.html) maybe? – WiredPrairie Jan 03 '13 at 13:45
  • I am not aware of a pymongo helper class that converts python class objects to BSON? – S-K' Jan 03 '13 at 17:36
  • What are you trying to do? [encode](http://api.mongodb.org/python/current/api/bson/index.html?highlight=bson#bson.BSON.encode) converts to BSON. – WiredPrairie Jan 03 '13 at 17:51

1 Answers1

3

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>
>>> 
Community
  • 1
  • 1
jhonkola
  • 3,385
  • 1
  • 17
  • 32
  • Thank you for the example, I decided to use ming as per your suggestion. – S-K' Jan 04 '13 at 13:19
  • I began development in ming, but it is a terrible ORM so we went for mongokit that is built nicely on top of pymongo – S-K' Mar 25 '13 at 16:03