Skip to content Skip to sidebar Skip to footer

Convert Mongodb Return Object To Dictionary

I'm using the bottle framework together with mongoengine. I have an orders model : class OrderDetail(Option): orderDetailsQty = FloatField() def to_dict(self): ret

Solution 1:

What about just using to_mongo method of an object to convert it to a dict?

object.to_mongo()

Solution 2:

Expanding on @alexvassel's and @z0r's answers, calling .to_mongo() converts the object to a SON instance. Once you have it, you can call its .to_dict() method to convert it to a dictionary.

For example... (qset is a queryset that's returned from mongoengine, after e.g. Posts.objects.all()).

sons = [ob.to_mongo() for ob in qset]
for son in sons:
    printstr(son.to_dict())

Solution 3:

import json
json.loads(yourobj.to_json())

Solution 4:

Extending on @alexvassel's answer, to_mongo() method returns SON object, which you can convert to dict by calling its to_dict() method

object.to_mongo().to_dict()

Solution 5:

you can custom method to convert object to dict

class Order(Document):
    userName = StringField(required=True)
    orderDate = DateTimeField()
    orderStatus = ListField(EmbeddedDocumentField(Status))
    orderDetails = ListField(EmbeddedDocumentField(OrderDetail))
    orderComments = ListField(EmbeddedDocumentField(Comment))
    isActive = BooleanField()

    def as_dict(self):
        return {
            "user_name": self.userName,
            "order_date": self.orderDate.strftime("%Y-%m-%d %H:%M:%S"),
        }

now you can use obj.as_dict() to dict

orders = Order.objects.all()
datas = [each.as_dict() for each in orders]

Post a Comment for "Convert Mongodb Return Object To Dictionary"