How to get dictionary object in Mongoengine Python?

Question:

On querying pymongo i get a dictionary object that can be sent directly as a response to the api request. Where as mongoengine returns a Document object on querying database. So I have to parse every object before it can be sent as the response in the api.

this is how I have to query in mongoengine.

users = User.objects(location = 'US')

This will return me a BaseQueryList object which contains User model type object. Instead I need that it should return me a list of dictionary type objects of Users.

Asked By: BabbarTushar

||

Answers:

In BaseQueryList there is one method called as_pymongo, we can use this to get rows as list of dict like where we get pymongo. The following is an example

users = User.objects(location = 'US').as_pymongo()

OR

In BaseQueryList there are in list of User class objects.

In User class object there is one method called _data, this will returns data as dict

So you can try like following

users = [user._data for user in users._iter_results()]

It could be help you.

Answered By: Syed Habib M

Mongoengine has to_mongo() method that gives you Python dict.

users = User.objects(location = 'US')
users.to_mongo()
Answered By: Vitalii Mytenko
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.