Menu Close

Create MongoDB Collection using Python

Create MongoDB Collection using Python

Hi Python programmers, In this guide, you will learn everything about How to create MongoDB collection using Python. In the previous tutorial, we have seen all about how to create a MongoDB database.

You have to remember one thing about MongoDB, MongoDB does not create any database until it gets content ( collections and documents ). So throughout this article, we will see all about the creation of collections in MongoDB with the help of Python.

At the end of this article, you wouldn’t have any confusion regarding creating MongoDB collection in Python.

Important Note:- Collections in MongoDB represent the table in SQL databases such as MySQL, PostgreSQL, etc.

Python MongoDB Create Collection

To create a MongoDB collection using Python, you need to follow below steps:

  • Create MongoClient object by providing proper IP of the machine.
  • Create the Database by providing name of the Database.
  • Create the collections by providing the name of the collection.

Example: Python MongoDB Create Collection


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

# database
database = myclient["programmingfundadb"]

# collections
coll = database["students"]
print(coll)

After the completed the execution of the above code, the output will look like this.

Output

Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'programmingfundadb'), 'students')

Note:- In MongoDB, a collection does not create until it gets content.

Check if collections exists

To check how many collections exist in the database, use list_collection_names() function which returns the list of all the collections names of the current database.

Note:- list_collection_names() the function returns a Python list of all the available collections.

Example: Check MongoDB Collections Exists or Not


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

# database
database = myclient["programmingfundadb"]

# collections
coll = database.list_collection_names()
print(coll)

Output

['Student', 'School']

As you can see in the above output only two collections are displayed but our newly created collections named students are not displayed because MongoDB does not create any collections until it gets content.
So in the next Python MongoDB tutorial, we will see how to insert a document (a record ) into database collection.

Conclusion

So in this guide we have seen create MongoDB collection using Python, In the next Python MongoDB tutorial, we will see how to insert documents in a collection with the help of proper examples.

I hope this article will help you, If you like this article, please share, support, and keep visiting for further Python MongoDB tutorials.

Thanks for Reading ….

Reference:- Click Here

Previous Article
Next Article

Related Posts