Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to access a collection in MongoDB using Python?

  • Last Updated : 17 May, 2020

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.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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 acces 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’)




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!