Get all documents of a collection using Pymongo

MAYA picture MAYA · Jun 21, 2016 · Viewed 85.4k times · Source

I want to write a function to return all the documents contained in mycollection in mongodb

from pymongo import MongoClient

if __name__ == '__main__':
    client = MongoClient("localhost", 27017, maxPoolSize=50)
    db=client.mydatabase
    collection=db['mycollection']
    cursor = collection.find({})
    for document in cursor:
        print(document)

However, the function returns: Process finished with exit code 0

Answer

notionquest picture notionquest · Jun 21, 2016

Here is the sample code which works fine when you run from command prompt.

from pymongo import MongoClient

if __name__ == '__main__':
    client = MongoClient("localhost", 27017, maxPoolSize=50)
    db = client.localhost
    collection = db['chain']
    cursor = collection.find({})
    for document in cursor:
          print(document)

Please check the collection name.