使用pymongo从mongodb动态获取数据

时间:2019-04-29 07:00:23

标签: python mongodb pymongo

我有一个名为my_db的mongodb数据库,它包含10个集合。我想从用户输入的任何集合中获取值。我想要一个界面,用户可以在其中选择一个集合以从中获取数据,然后他找到根据他的输入从集合中动态获取数据。我是该领域的新手,所以我在执行此操作时遇到了很多问题。请帮助我。 并预先感谢

我创建了一个界面,用户可以从数据库中选择集合并找到其字段。

import pymongo
from pymongo import MongoClient
from bson.json_util import dumps


mon_con = MongoClient('localhost', 27017)
mon_db = mon_con.my_db

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)

0 个答案:

没有答案