Open In App

How to access a collection in MongoDB using Python?

Improve
Improve
Like Article
Like
Save
Share
Report

MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. MongoDB offers high speed, high availability, and high scalability.

Accessing a Collection

1) Getting a list of collection: For getting a list of a MongoDB database’s collections list_collection_names() method is used. This method returns a list of collections.
Syntax:

list_collection_names()

 
Example:
 

Sample Database:

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")


Output:

collections: ['Geeks'] 

2) Check if the collection exist or not: To check if the collection attribute exists for the database use hasattr() method. It returns true if the collection is in database otherwise returns false. 

Syntax: hasattr(db, ‘collectionname’)

Parameters:
db: It is database object. 
collectionname: It is the name of the collection. 

Example:

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'))


Output:

True

3) Accessing a Collection: To access a MongoDB collection name use the below syntax. 
 

Syntax:

database_object.Collectionname
or
database_object["Collectionname"]

Note: Database_object[“Collectioname”] can be useful in the case where the name of the collection contains a space in between them i.e. in cases like database_object[“Collection name”].
Example:

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)


 
Output: 

Collection: Collection(Database(MongoClient(host=[‘localhost:27017’], document_class=dict, tz_aware=False, connect=True), ‘GFG’), ‘gfg’)



Last Updated : 30 May, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads