In Python, To establish a connection between the MongoDB Client database and Python programming language. we need first to install the "pymongo" module.
In MongoDB, we don't need to explicitly create a database. MongoDB creates a database automatically when we first store data in it.
However, we can switch to a specific database or check if it exists.
Here's how we can handle database creation and switching in Python using "pymongo":
After importing "pymongo", we must provide a connection URL and database name to MongoClient.
# import pymongo library import pymongo # Connection URL and database name uri = "mongodb://localhost:27017/" database_name = "your_database_name" # Connect to MongoDB server client = pymongo.MongoClient(uri)
Check if the database exists in MongoDB Server.
if database_name in client.list_database_names(): print(f"The database '{database_name}' already exists.") else: print(f"The database '{database_name}' does not exist.")
We can also explicitly access a database using the below syntax.
db = client.your_database_name
# import pymongo library import pymongo # Connection URL and database name uri = "mongodb://localhost:27017/" database_name = "your_database_name" # Connect to MongoDB server client = pymongo.MongoClient(uri) # Check if the database exists if database_name in client.list_database_names(): print(f"The database '{database_name}' already exists.") else: print(f"The database '{database_name}' does not exist.") # Access or create the database db = client[database_name] # We can also explicitly access a database like this: # db = client.your_database_name
Replace "mongodb://localhost:27017/" with the connection string for your MongoDB server.
Replace "your_database_name" with the name of the database you want to create or access.
The "list_database_names()" method is used to get a list of all database names on the MongoDB server.
If the specified database name exists, it prints a message indicating that the database already exists. Otherwise, it prints a message indicating that the database does not exist.
Finally, it accesses or creates the specified database using the "client[database_name]" syntax.
The below commands will display the database list from the MongoDB Client and collections list from specific Database.
# show databases will list all databases show dbs; # check for collections within databases show collections
Remember that MongoDB automatically creates a database when we first store data in it.
So, we don't need to explicitly create a database unless we want to check its existence or switch to it.