Jean loriston
Jean loriston

Reputation: 49

How can i return all values from for loop in python3 mongodb query

I have a function that queries a mongodb collection

def checkDb():
    signals =  mydb['collection']
    findInMongo =  signals.find({}, {'_id': False})
    for x in findInMongo:
        return x

I want to return everything from the collection without printing it to the console. When I run the above code I get one result:

{'Date': testvalue, 'Open': testvalue, 'High': testvalue, 'Low': testvalue, 'Close': testvalue, 'Volume':testvalue}

When I run

def checkDb():
    signals =  mydb['collection']
    findInMongo =  signals.find({}, {'_id': False})
    for x in findInMongo:
        print(x)

I get every single document from my collection, which is what i want. How can i make the code return every single document instead of using print?

Upvotes: 0

Views: 97

Answers (1)

C.Nivs
C.Nivs

Reputation: 13106

The problem is that you are using return, when you probably want yield:

def checkDb():
    signals =  mydb['collection']
    findInMongo =  signals.find({}, {'_id': False})
    for x in findInMongo:
        return x # This will exit after the first result

return exits the function, it literally returns a value from the function, exiting scope. yield on the other hand, will keep producing values until the iterator is exhausted (or findInMongo has no more elements in the for loop).

Instead, do

def checkDb():
    signals =  mydb['collection']
    findInMongo =  signals.find({}, {'_id': False})
    for x in findInMongo:
        yield x

# which allows you to do
vals = list(checkDb())

Because checkDb() is now an iterator (or more specifically, a generator). Later versions of python3 also introduced the nice-looking yield from syntax

def checkDb():
    signals =  mydb['collection']
    findInMongo =  signals.find({}, {'_id': False})
    yield from findInMongo # yield from a collection directly

Or, you could just return findInMongo if that is an iterator

def checkDb():
    signals =  mydb['collection']
    findInMongo =  signals.find({}, {'_id': False})
    return findInMongo # return the iterator directly

All of these will support list(checkDb()) or [x for x in checkDb()] syntax

Upvotes: 1

Related Questions