How to find names of all collections using PyMongo?

后端 未结 5 935
北恋
北恋 2021-02-01 00:43

How to find names of all collections using PyMongo and find all fields in chosen collection ? I have name of database and name of chosen collection. (Scenario : user input name

5条回答
  •  清酒与你
    2021-02-01 01:09

    Here is a script that I created that does essentially what you want.

    It displays a list of all collections in the database (in this case the 'dh' database). The user types the collection of choice and the script displays the fields and fields within documents down 2 levels. It displays in mongo entry format, which can be copied directly into a mongo query. It also will check the first level fields for lists of dictionaries and display those subfields in lists surrounded by brackets 'field.[subfield_in_list]' .

    There is also optional command line input of collection name (e.g. python path/to/script/scriptname.py collection_name

    import pymongo
    from pymongo import Connection
    
    mon_con = Connection('localhost', 27017)
    mon_db = mon_con.dh
    
    cols = mon_db.collection_names()
    for c in cols:
        print c
    col = raw_input('Input a collection from the list above to show its field names: ')
    
    collection = mon_db[col].find()
    
    keylist = []
    for item in collection:
        for key in item.keys():
            if key not in keylist:
                keylist.append(key)
            if isinstance(item[key], dict):
                for subkey in item[key]:
                    subkey_annotated = key + "." + subkey
                    if subkey_annotated not in keylist:
                        keylist.append(subkey_annotated)
                        if isinstance(item[key][subkey], dict):
                            for subkey2 in item[subkey]:
                                subkey2_annotated = subkey_annotated + "." + subkey2
                                if subkey2_annotated not in keylist:
                                    keylist.append(subkey2_annotated)
            if isinstance(item[key], list):
                for l in item[key]:
                    if isinstance(l, dict):
                        for lkey in l.keys():
                            lkey_annotated = key + ".[" + lkey + "]"
                            if lkey_annotated not in keylist:
                                keylist.append(lkey_annotated)
    keylist.sort()
    for key in keylist:
        keycnt = mon_db[col].find({key:{'$exists':1}}).count()
        print "%-5d\t%s" % (keycnt, key)
    

    I'm sure you could write a function to iterate down levels infinitely until there is no data left, but this was quick and dirty and serves my needs for now. You could also modify to show the fields for just a particular set of records in a collection. Hope you find it useful.

提交回复
热议问题