Python MongoDB create database

Create database

To create a database in MongoDB, you first need to create a MongoClient object, and then specify the connection URL with the correct IP address and the name of the database to be created.

If the database does not exist, MongoDB will create the database and establish a connection.

Instance

Create a database named "mydatabase":

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]

Run Instance

Important Note:A database in MongoDB will not be created before obtaining content!

Before actually creating a database (and collection), MongoDB will keep waiting for you to create a collection (table) that has at least one document (record).

Check if the database exists

Remember: In MongoDB, a database will not be created before obtaining content, so if this is your first time creating a database, you should complete the next two chapters (Creating Collections and Creating Documents) before checking if the database exists!

You can check if a database exists by listing all the databases in the system:

Instance

Return the list of databases in the system:

print(myclient.list_database_names())

Run Instance

Or you can check a specific database by name:

Instance

Check if "mydatabase" exists:

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

Run Instance