Mongoengine: How do I print the values of all fields of a Mongoengine document?

Created on 1 Dec 2016  路  2Comments  路  Source: MongoEngine/mongoengine

I have a Mongoengine document (in fact EmbeddedDocument) and want to print all the values of its fields. How do I do that?

e.g.:

class MyDocument(Document):
    foo = fields.StringField()
    bar = fields.IntField()

and I'd like to print it like this:

    MyDocument({
        "id": ObjectId("507f1f77bcf86cd799439011"),
        "foo": "question of life universe and everything"
        "bar": "42"
    })

Most helpful comment

@wojcikstefan
Eventually I used to_mongo() and it solved my problem. Thanks!

All 2 comments

There's no way that prints it by default in the exact form you want.

The simplest/fastest way is to call doc.to_json() which will print this:

In [21]: class EmbeddedDoc(mongoengine.EmbeddedDocument):
    baz = mongoengine.fields.StringField()
   ....:

In [22]: class MyDocument(mongoengine.Document):
    foo = mongoengine.fields.StringField()
    bar = mongoengine.fields.IntField()
    embedded = mongoengine.fields.EmbeddedDocumentListField(EmbeddedDoc)
   ....:

In [23]: doc = MyDocument.objects.create(foo='foo', bar=123, embedded=[EmbeddedDoc(baz='baz'), EmbeddedDoc(baz='bar')])

In [24]: doc.to_json()
Out[24]: '{"_id": {"$oid": "58404ba2c6e47b1d38b7750f"}, "foo": "foo", "bar": 123, "embedded": [{"baz": "baz"}, {"baz": "bar"}]}'

You could also do dict(doc.to_mongo()) which has the benefit of looking more like what you wanted, but it's not recursive:

In [25]: dict(doc.to_mongo())
Out[25]:
{'_id': ObjectId('58404ba2c6e47b1d38b7750f'),
 'bar': 123,
 'embedded': [SON([('baz', u'baz')]), SON([('baz', u'bar')])],
 'foo': u'foo'}

This can get you in trouble, but you could also override the __repr__ method (I would advise against that though):

In [42]: class MyDocument(mongoengine.Document):
    foo = mongoengine.fields.StringField()
    bar = mongoengine.fields.IntField()
    embedded = mongoengine.fields.EmbeddedDocumentListField(EmbeddedDoc)

    def __repr__(self):
        doc_name = self.__class__.__name__
        doc_dict = self.to_json()
        return '%s(%s)' % (doc_name, repr(doc_dict)[1:-1])
   ....:

In [43]: doc = MyDocument.objects.create(foo='foo', bar=123, embedded=[EmbeddedDoc(baz='baz'), EmbeddedDoc(baz='bar')])

In [44]: print repr(doc)
MyDocument({"_id": {"$oid": "58404d34c6e47b1d38b77511"}, "foo": "foo", "bar": 123, "embedded": [{"baz": "baz"}, {"baz": "bar"}]})

@wojcikstefan
Eventually I used to_mongo() and it solved my problem. Thanks!

Was this page helpful?
0 / 5 - 0 ratings