Hi Programmers, In this article, we are going to see how to create MongoDB database in python with the help of the PyMongo library. In the previous tutorial, we have seen all about How to install PyMongo using the pip command.
Headings of Contents
Create Mongodb Database in Python
To create a database in MongoDB, firstly we need to create a MongoClient object by specifying a connection URL with the proper name of the IP address, Then we can perform all the operations.
To Create MongoDB Database in Python, we need to provide a database name to MongoClient object within a square bracket as a string means double-quotes.
You can follow the following example to create MongoDB Database using Python.
Example: Python MongoDB Create Database
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") db = myclient["programmingfundadb"] print(db)
In the above example, we specify a database name programmingfundadb. After successful execution of the above code, MongoDB creates a database and makes a connection to it.
Your output looks something like this.
Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'programmingfundadb')
Important Note:- MongoDB does not create a database until it gets content ( collections and documents ).In MongoDB, collections represent a table in SQL Database and documents represent records in a table in SQL database.
Check Database Exits
Remember:- MongoDB does not create a database until its get content, So you should have wait for next two tutorials where we will see create document and collections in the MongoDB database.
You can display all the existing databases in MongoDB by using the
list_database_names() function returns a list of all the databases.
Example: Check MongoDB Database Exists or Not
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") databases = myclient.list_database_names() print(databases)
['admin', 'config', 'local']
As you can see in the above output, we are not able to see our newly created database because so far we are not created any document and collection in that database.
In the next Python MongoDB article, we will see how to create MongoDB collections.
So far, we have seen create MongoDB database using python. You have to remember always one thing when you create a MongoDB database, Then MongoDB does not display that database until it gets content.
In the next MongoDB article, we have seen all about how to create MongoDB collections with the help of examples.
I hope this article is helpful for you. if you like this article, please support and keep visit for further Python MongoDB tutorials.
Thanks for reading …
Reference:- Click Here