BabbarTushar
BabbarTushar

Reputation: 1335

How to get dictionary object in Mongoengine Python?

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.

Upvotes: 3

Views: 5769

Answers (2)

Vitalii Mytenko
Vitalii Mytenko

Reputation: 772

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

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

Upvotes: 1

Syed Habib M
Syed Habib M

Reputation: 1817

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.

Upvotes: 9

Related Questions