2012-03-21 3 views

답변

5

다음은 필자가 원하는 스크립트를 작성한 것입니다.

데이터베이스 (이 경우 'dh'데이터베이스)에 모든 모음의 목록을 표시합니다. 사용자가 선택 컬렉션을 입력하면 스크립트는 문서 내의 필드와 필드를 2 단계 아래로 표시합니다. mongo 항목 형식으로 표시되며 mongo 쿼리에 직접 복사 할 수 있습니다. 또한 사전 목록의 첫 번째 레벨 필드를 검사하고 대괄호 '[subfield_in_list]'로 묶인 목록에서 해당 하위 필드를 표시합니다.

컬렉션 이름의 옵션 명령 행 입력 (예를 들어 파이썬 경로 /로/스크립트/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) 

난 당신이 때까지 무한히 수준을 반복하는 함수를 작성할 수 있습니다 확신이 데이터가 남아 있지 않지만 빠르고 간단하며 내 요구에 부합합니다 컬렉션의 특정 레코드 세트에 대한 필드를 표시하도록 수정할 수도 있습니다. 유용하다고 생각하길 바랍니다.

11

이것은 매우 유용합니다. 간단합니다. 예 :

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) 

결과 -> { "database1"[ "collection1", "collection2"..., "DATABASE2"[...], ...} 같은

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

MongoDB 데이터베이스에서 모든 컬렉션 이름을 가져 오기 위해 항상이 방법을 사용했습니다.

import pymongo 
db_connect = pymongo.MongoClient('192.168.4.202', 20020) 
database_name = 'MY_DATABASE_NAME' 
database = db_connect[database_name] 
collection = database.collection_names(include_system_collections=False) 
for collect in collection: 
    print collect