Home:ALL Converter>pymongo get keys of all collections

pymongo get keys of all collections

Ask Time:2021-03-12T19:14:38         Author:KillRoy27

Json Formatter

I need a code that will show me the main keys of all collection names. I want to be able to use this on different mongo instances so I don't want to use the exact name of collections.

import pymongo
import sys
import json

    from pymongo import MongoClient
    
    
        if __name__ == '__main__':
            client = pymongo.MongoClient("localhost", 27017, maxPoolSize=50)
            db = client.list_database_names()
            document = db.collection_name.find_one()
            for k in document:
                print(k)

but when I run it, it outputs

Traceback (most recent call last):
  File "bla.py", line 12, in <module>
    document = db.collection_name.find_one()
AttributeError: 'list' object has no attribute 'collection_name'

What is wrong here?

Author:KillRoy27,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/66598870/pymongo-get-keys-of-all-collections
yy