使用 PyMongo 获取所有集合的名称
PyMongo是用于使用Python建立与 MongoDB 的连接并执行插入、删除、更新等所有操作的模块。 PyMongo 是使用 MongoDB 和Python的推荐方式。
注意:有关Python和 MongoDB 的详细信息,请访问 MongoDB 和Python。
让我们从使用 PyMongo 获取所有集合的名称开始
- 导入 PyMongo 模块:使用以下命令导入 PyMongo 模块:
from pymongo import MongoClient
如果您的机器上尚未安装 MongoDB,您可以参考指南:使用Python安装 MongoDB 的指南
- 创建连接:现在我们已经导入了模块,是时候建立与 MongoDB 服务器的连接了,大概是在 localhost(主机名)的端口 27017(端口号)上运行。
client = MongoClient(‘localhost’, 27017)
- 访问数据库:因为与 MongoDB 服务器的连接已建立。我们现在可以创建或使用现有的数据库。
mydatabase = client.name_of_the_database
在我们的例子中,数据库的名称是 GeeksForGeeks
mydatabase = client.GeeksForGeeks
- 列出数据库中所有集合的名称:列出数据库中所有集合的名称。
mydatabase.collection_names()
collection_names() 在 3.7.0 版中已弃用。而是使用
mydatabase.list_collection_names()
此方法返回数据库中的集合列表。
例子:
样本数据库:
# Python Program to demonstrate
# List name of all collections using PyMongo
# Importing required libraries
from pymongo import MongoClient
# Connecting to MongoDB server
# client = MongoClient('host_name', 'port_number')
client = MongoClient(‘localhost’, 27017)
# Connecting to the database named
# GeeksForGeeks
mydatabase = client.GeeksForGeeks
# Getting the names of all the collections
# in GeeksForGeeks Database.
collections = mydatabase.list_collection_names()
# Printing the name of the collections to the console.
print(collections)
输出:
['Geeks']