Reputation: 3869
I have a MongoDB database that has stock data stored on it. Each stock data is stored as a separate collection that the collection name is the stock name, and there are id, time, open, high, low, close, volume
data stored in each collection for some days for each stock.You can see the structure of each collection in picture below:
What I am trying to do is to find each collection, and store it's data as a new python dictionary separately. But my code doesn't work properly no errors.
from pymongo import MongoClient
from pprint import pprint
myclient = MongoClient("mongodb://localhost:27017/") #, username='mongo-admin', password='password')
mydb = myclient["db-data-stock"]
pprint(mydb)
posts = mydb.list_collection_names()
for item in posts:
for data in item:
pprint(data)
And it only prints the name of the collections not the data inside of them!
The output of the posts
is a list with contents like:
['کیمیا',
'ونفت',
'اخزا807',
'دیران',
'وزمین',
'کحافظ',
'لبوتان']
And the output of nested for
s is like:
'ر'
'ک'
'ب'
'ا'
'ف'
'ق'
'ث'
'ج'
'و'
'ا'
'ن'
'ک'
'ی'
'ش'
Upvotes: 1
Views: 537
Reputation: 3349
You are trying to iterate over collection name (which is a string) instead of its MongoDB-cursor
I think the below code is what you are looking for:
from pymongo import MongoClient
from pprint import pprint
myclient = MongoClient("mongodb://localhost:27017/") #, username='mongo-admin', password='password')
mydb = myclient["db-data-stock"]
pprint(mydb)
posts = mydb.list_collection_names()
for item in posts:
for data in mydb[item].find({}):
pprint(data)
Upvotes: 2