BA必备,获取MongoDB某DB所有collection和其中字段属性

其实MongoDB是可以混用滴,只是单位特殊的情况可以用一下(因为各字段都是单纯数据类型)。

from pymongo import MongoClient
import pandas as pd

client = MongoClient('mongodb://ttt:[email protected]:27017/')
db = client.datahub

collection_list = db.list_collection_names()

def main():
    results = []
    for collection_d in collection_list:
        results.append((collection_d,''))
        coll = db.get_collection(collection_d)
        d = coll.find_one()
        for i,j in d.items():
            if i == '_id':
                continue
            #print(i,j)
            results.append(('   '+i,type(j)))  #hack method_grab the first row of the data and check its type
                                                #注意这种方式可能会有none type.

    client.close()
    print(results)

    df = pd.DataFrame(results)
    df.to_csv('~/mongoDB_table_info.csv',header=False,index=False,mode='w')


if __name__ == '__main__':
    main()

 

你可能感兴趣的:(Python,pymongo)