Thiago Schons
Thiago Schons

Reputation: 1

Can`t print values from collections in pymongo

I'm trying to get the values of all databases existing in mongodb, iterate over all databases and collections for than print it documents. I can to print the document passing the collection as a variable, but can`t do it iterating over all databases and collections (as the value of variable). Someone knows if pymongo supports to do it dynamically passing as value and not passing the collection and the database as the variable itself??

client = MongoClient('mongodb://localhost:27017/')

names = client.database_names()
for dbName in names:
    print(dbName)
    db = client.dbName
    collectionNames = client[dbName].collection_names()
    for colecao in collectionNames: 
        print(colecao)
        cursor = db.colecao # choosing the collection you need
        print(cursor)
        cursor2 = cursor.find()  # get documents
        for document in cursor2:
            pprint(document)

The database names and collection names print normally, but the print cursor returns: "Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), u'dbName'), u'colecao')"

It goes with the name of variables.

Upvotes: 0

Views: 442

Answers (1)

Prashanti
Prashanti

Reputation: 173

Instead of

client.dbName

use

client.get_database(dbName)

and instead of

cursor = db.colecao

use

cursor = db.get_collection(colecao)

Upvotes: 0

Related Questions