How to find names of all collections using PyMongo?

后端 未结 5 1755
遇见更好的自我
遇见更好的自我 2021-02-01 00:08

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 00:52

    This is very simple. e.g.

    import pymongo
    import json
    
    if __name__ == '__main__':
        client = pymongo.MongoClient("localhost", 27017, maxPoolSize=50)
        d = dict((db, [collection for collection in client[db].collection_names()])
                 for db in client.database_names())
        print json.dumps(d)
    

    result -> {"database1":["collection1","collection2"...], "database2": [...], ...}, like:

    {"test": ["score", "test4", "test5", "test6", "test3", "test7", "user", "test2", "test8"],
     "testdb": ["test5", "test8", "test2", "test9", "test3", "test4", "test6", "test"],
     "local": ["startup_log"],
     "stackoverflow": ["questions"]}
    

提交回复
热议问题