如何使用Python访问 MongoDB 中的集合?
MongoDB是一个跨平台、面向文档的数据库,它基于集合和文档的概念。 MongoDB 提供高速、高可用性和高可扩展性。
访问集合
1) 获取集合列表:为了获取 MongoDB 数据库的集合列表,使用 list_collection_names() 方法。此方法返回集合列表。
句法:
list_collection_names()
例子:
样本数据库:
Python3
from pymongo import MongoClient
# create an client instance of the
# MongoDB class
mo_c = MongoClient()
# create an instance of 'some_database'
db = mo_c.GFG
# get a list of a MongoDB database's
# collections
collections = db.list_collection_names()
print ("collections:", collections, "\n")
Python3
from pymongo import MongoClient
# create an client instance of
# the MongoDB class
mo_c = MongoClient()
# create an instance of 'some_database'
db = mo_c.GFG
# check collection is exists or not
print(hasattr(db, 'Geeks'))
Python3
from pymongo import MongoClient
# create an client instance of
# the MongoDB class
mo_c = MongoClient()
# create an instance of 'some_database'
db = mo_c.GFG
col1 = db["gfg"]
print ("Collection:", col1)
输出:
collections: ['Geeks']
2) 检查集合是否存在:要检查数据库的集合属性是否存在,请使用 hasattr() 方法。如果集合在数据库中,则返回 true,否则返回 false。
Syntax: hasattr(db, ‘collectionname’)
Parameters:
db: It is database object.
collectionname: It is the name of the collection.
例子:
Python3
from pymongo import MongoClient
# create an client instance of
# the MongoDB class
mo_c = MongoClient()
# create an instance of 'some_database'
db = mo_c.GFG
# check collection is exists or not
print(hasattr(db, 'Geeks'))
输出:
True
3) 访问集合:要访问 MongoDB 集合名称,请使用以下语法。
句法:
database_object.Collectionname
or
database_object["Collectionname"]
注意: Database_object[“Collectionname”] 在集合名称之间包含空格的情况下很有用,例如在 database_object[“Collection name”] 等情况下。
例子:
Python3
from pymongo import MongoClient
# create an client instance of
# the MongoDB class
mo_c = MongoClient()
# create an instance of 'some_database'
db = mo_c.GFG
col1 = db["gfg"]
print ("Collection:", col1)
输出:
Collection: Collection(Database(MongoClient(host=[‘localhost:27017’], document_class=dict, tz_aware=False, connect=True), ‘GFG’), ‘gfg’)