简体   繁体   English

如何使用 PyMongo 查找所有集合的名称?

[英]How to find names of all collections using PyMongo?

How to find names of all collections using PyMongo and find all fields in chosen collection ?如何使用 PyMongo 查找所有集合的名称并查找所选集合中的所有字段? I have name of database and name of chosen collection.我有数据库名称和所选集合的名称。 (Scenario : user input name of database, need to find all collections and show in dropdown list, when user click on one item need to find all fields in that collection) (场景:用户输入数据库名称,需要查找所有集合并显示在下拉列表中,当用户单击一项时需要查找该集合中的所有字段)

To find the collections, you can use collection_names() - http://api.mongodb.org/python/current/api/pymongo/database.html#pymongo.database.Database.collection_names要查找集合,您可以使用collection_names() - http://api.mongodb.org/python/current/api/pymongo/database.html#pymongo.database.Database.collection_names

Edit:编辑:

The collection_names is deprecated from 3.7 onwards and been replaced by list_collection_names - https://api.mongodb.com/python/current/api/pymongo/database.html#pymongo.database.Database.list_collection_names collection_names3.7开始被弃用,被list_collection_names取代 - https://api.mongodb.com/python/current/api/pymongo/database.html#pymongo.database.Database.list_collection_names

This is very simple.这很简单。 eg例如

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 :结果 -> {"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"]}

I always used this way to get all collection names from my MongoDB database.我总是使用这种方式从我的 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

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).它显示数据库中所有集合的列表(在本例中为“dh”数据库)。 The user types the collection of choice and the script displays the fields and fields within documents down 2 levels.用户键入选择的集合,脚本将文档中的字段和字段显示在 2 级以下。 It displays in mongo entry format, which can be copied directly into a mongo query.它以 mongo 条目格式显示,可以直接复制到 mongo 查询中。 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]' .它还将检查字典列表的第一级字段,并在括号 'field.[subfield_in_list]' 包围的列表中显示这些子字段。

There is also optional command line input of collection name (eg python path/to/script/scriptname.py collection_name还有可选的命令行输入集合名称(例如 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.希望你觉得它有用。

DeprecationWarning: collection_names is deprecated.弃用警告:不推荐使用 collection_names。 Use list_collection_names instead.请改用 list_collection_names。

Changed in version 3.7: Deprecated.在 3.7 版更改:已弃用。 Use list_collection_names() instead.请改用 list_collection_names()。

An example to read the database name from user input and then finding the list collection names would be:从用户输入读取数据库名称然后查找列表集合名称的示例是:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

dbname = input("Enter database name: ")
mydb = myclient[dbname]

#list the collections
for coll in mydb.list_collection_names():
    print(coll)

Reference: Python MongoDB参考: Python MongoDB

A simplest code would be using pymongo :最简单的代码是使用 pymongo :

from pymongo import MongoClient
client = MongoClient('localhost',27017)
database = client.database_name
print(database.list_collection_names())

As a beginner I find the official documents of MongoDB and pymongo challenging to understand / digest.作为初学者,我发现 MongoDB 和 pymongo 的官方文档难以理解/消化。 In addition api changes are making it harder to find relevant code examples.此外,api 更改使查找相关代码示例变得更加困难。 I would expect that the basic official tutorial to start with the following:我希望基本的官方教程从以下内容开始:

from pymongo import MongoClient

db_url = 'mongodb://localhost:27017/test' # or some other default url
client = MongoClient(db_url)
db=client.admin

# Sanity check - we get server status
print(db.command("serverStatus"))

# Available databases    
print(client.list_database_names())

# Available collections in a specific database
print(db.list_collection_names())

# Bonus: A scheme of relation among databases / collections / documents

 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM