Converting mongoengine objects to JSON

Kaushik Makwana picture Kaushik Makwana · Apr 26, 2017 · Viewed 10.1k times · Source

i tried to fetch data from mongodb using mongoengine with flask. query is work perfect the problem is when i convert query result into json its show only fields name.

here is my code

view.py

from model import Users
result = Users.objects()
print(dumps(result))

model.py

class Users(DynamicDocument):
    meta = {'collection' : 'users'}
    user_name = StringField()
    phone = StringField()

output

[["id", "user_name", "phone"], ["id", "user_name", "phone"]]

why its show only fields name ?

Answer

Joe Walsh picture Joe Walsh · Jun 2, 2017

Your query returns a queryset. Use the .to_json() method to convert it.

Depending on what you need from there, you may want to use something like json.loads() to get a python dictionary.

For example:

from model import Users
# This returns <class 'mongoengine.queryset.queryset.QuerySet'>
q_set = Users.objects()
json_data = q_set.to_json()

# You might also find it useful to create python dictionaries
import json
dicts = json.loads(json_data)