0

I am reading all collections of a mongodb database and the same time looping collection name in for loop to get each collection data dynamically using pymongo.

this is running on python 3.7 and mongodb 3.4 with pymongo

from pymongo import MongoClient
from bson.objectid import ObjectId
import json


client = MongoClient("localhost", 27017, maxPoolSize=50)
#print(client)
mydatabase = client["testdb"]

collections = mydatabase.collection_names(include_system_collections=False)

for collectionName in collections:
    print(collectionName)

    mydata = mydatabase.collectionName.find({})

    for value in mydata:
        print(value)
        for key,valueOFproject in value:
            print(key)
            print(value)

Db

1st collection

{
    "_id" : "hiphdkTest_HIPHDK_76P1_P00_19WW09Test",
    "project" : "hiphdktest",
    "config" : "HIPHDK_76P1_P00_19WW09test",
    "manual" : {
        "tag1" : "fdsfsdfsd",
        "No" : "No",
        "prqdata1" : "fsdfadfasdfasdfsdfsd",
        "admin1" : "dbhiphdk"
    }
}

2nd collection

{
    "_id" : "hiphdk_HIPHDK_76P1_P00",
    "project" : "hiphdk",
    "config" : "HIPHDK_76P1_P00",
    "manual" : {
        "tag1" : "fdsfsdfsd",
        "No" : "No",
        "prqdata1" : "fsdfadfasdfasdfsdfsd",
        "admin1" : "dbhiphdk"
    }
}

3rd collection

{
    "_id" : "hiphdk_HIPHDK_76P1_P00_19WW09",
    "project" : "hiphdk",
    "config" : "HIPHDK_76P1_P00_19WW09",
    "manual" : {
        "tag1" : "fdsfsdfsd",
        "No" : "No",
        "prqdata1" : "fsdfadfasdfasdfsdfsd",
        "admin1" : "dbhiphdk"
    }
}

only getting collection names

hiphdk_HIPHDK_76P1_P00_19WW09 hiphdk_HIPHDK_76P1_P00 hiphdkTest_HIPHDK_76P1_P00_19WW09Test

it should print collection names and data of each collection.

1 Answer 1

2

The key change is this line mydata = mydatabase[collectionName].find({})

See if this gives you what you need:

from pymongo import MongoClient
from bson.json_util import dumps

client = MongoClient("localhost", 27017, maxPoolSize=50)
mydatabase = client["testdb"]

collections = mydatabase.list_collection_names(include_system_collections=False)

for collectionName in collections:
    mydata = mydatabase[collectionName].find({})
    for value in mydata:
        print(dumps(value))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.