How to load data from Mongodb to a variable?

20 views
Skip to first unread message

Dakshina R

unread,
Dec 21, 2017, 3:03:56 PM12/21/17
to mongodb-user
Hi,
I am new to Mongodb.I have learned to insert query and delete data in Mongodb.Now , for my application I need to read the data stored in Mongodb as a dictionary and store it in a variable.I use a Tornado framework for my web application

when i do:

cursor = db.user.find()
for document in cursor:
       
print(document)

It prints:

{u'_id': ObjectId('5a3b3e4a122b2d0e69e5d6b5'), u'testing': {u'uid': u'testing', u'name': u'test', u'phone': u'1234567890'}}

{u'_id': ObjectId('5a3b3e4a122b2d0e69e5d6b6'), u'testing1': {u'uid': u'testing1', u'name': u'test1', u'phone': u'1234567891'}}

I want to store this entire data into a variable(result) as a dictionary.How do I do that?

Wan Bachtiar

unread,
Jan 9, 2018, 7:58:35 PM1/9/18
to mongodb-user

I want to store this entire data into a variable(result) as a dictionary.How do I do that?

Hi Dakshina,

A Python dictionary is indexed by keys, with the requirement that the keys are unique within one dictionary. Depending on your use case, you can utilise the ObjectId (converted to string) returned as keys for your result dictionary.
For example:

cursor = db.user.find()
result = dict()
for document in cursor:
    result[str(document["_id"])] = document

For questions that are related more to the use of Python language itself, i.e. converting an iterator into a Python dictionary , you can also post on StackOverflow Python to reach wider audience.

Regards,
Wan.

Reply all
Reply to author
Forward
0 new messages