0

Im have some data from my collection at mongoDb i want to see all data from specified collection let say i've simple code like this

from pymongo import MongoClient

url = 'my url'
client = MongoClient(url, ssl=True, retryWrites=True)

class DB(object):
    def __init__(self):
        self.db = client.mydb
        self.col = self.db.mycol

    def see_listed(self):
        for i in self.col.find():
             return i

db = DB()
print(db.see_listed())

That only returned one data from my collection

but if i changed code from see_listed to

for i in self.col.find():
    print(i)

That return all of data from my collection,where my wrong i don't know.. I just read some documents at try like this.

Im so thankful for any help im appreciate

alnyz
  • 91
  • 1
  • 1
  • 9

1 Answers1

0

You only get one document since you use return in your see_listed function.

If you change the return to yield instead it should return a generator you can iterate through.

def see_listed(self):
    for i in self.col.find():
         yield i

But if you only want the data in a list you could do:

def see_listed(self):
    return list(self.col.find())

Maybe not the best choice if the size of the data is unknown.

yield keyword: What does the "yield" keyword do?

oste-popp
  • 190
  • 1
  • 10