Thursday, 12 January 2023

Python MongoDB Create Database

 To create a database in MongoDB, start by creating a MongoClient object, then specify a connection URL with the correct ip address and the name of the database you want to create.

MongoDB will create the database if it does not exist, and make a connection to it.

You can check if a database exist by listing all databases in you system:

Return a list of your system's databases

import pymongo

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

mydb = myclient["mydatabase"]

print(myclient.list_database_names())

Or you can check a specific database by name

Check if "mydatabase" exists

dblist = myclient.list_database_names()
if "mydatabase" in dblist:
  print("The database exists.")


Share:

0 comments:

Post a Comment