How to create a database in MongoDB using Python
Hey programmers, in this tutorial, we are going to learn how to create a database in MongoDB using Python. Before jumping to the tutorial on how to create a MongoDB database in Python we first need to establish a connection that is covered in the previous section.
If you don’t know how to connect the MongoDB to python using pymongo package then you can check our previous tutorial where we have shown the complete process establishing a connection between MongoClient and Python.
In this section, we will cover how to create a database in MongoDB using Python.
Creating the database in MongoDB using Python
To create the database follow these steps:
- Establish a connection from MongoDB to python using MongoClient.
- Using the reference created during connection we can create the database.
- Use the below Python Program to create a database in MongoDB
from pymongo import MongoClient mongo = MongoClient('localhost', 27017) db = mongo.CodeSpeedy print(db)
Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'testdb')
The first line of code is an import statement for importing MongoClient. Once MongoClient is imported we establish a connection from MongoDB to python. After the successful establishment of the connection, we are ready to create the database.
db = mongo.test
This is the code in which we will create the database. Here db is the reference used for the database. test is the name of the database and mongo is the reference that connects python to MongoClient.
The name of the database can be anything as per your choice and the same goes for the reference variable.
MongoDB will create a new database test as no such database is present in the MongoDB database. Actually the database is created only when we add some data into the collection of the test database. If there exists a test database in the MongoDB database then it will open that database.