Get all documents of a collection using Pymongo
PythonMongodbPymongoPython Problem Overview
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
Python Solutions
Solution 1 - Python
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.
Solution 2 - Python
pymongo creates a cursor. Hence you'll get the object 'under' the cursor. To get all objects in general try:
list(db.collection.find({}))
This will force the cursor to iterate over each object and put it in a list()
Have fun...
Solution 3 - Python
I think this will work fine in your program.
cursor = db.mycollection # choosing the collection you need
for document in cursor.find():
print (document)
Solution 4 - Python
it works fine for me,try checking the exact database name and collection name.
and try changing from db=client.mydatabase
to db=client['mydatabase']
.
If your database name is such that using attribute style access won’t work (like test-database), you can use dictionary style access instead. source !