Python MongoDB Create Database

Python MongoDB Create Database

Creating a Database

Start by generating a MongoClient object, then specify a connection URL with the correct ip address and the name of database you wish to build to construct a MongoDB database.

If it doesn't exist, MongoDB will create and connect to the database.

Example :- Create a database called "mydatabase" :

import pymongo
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = myclient['mydatabase']
print("Database created!")

Output :-

Database created!

Important: A database is not formed in MongoDB unless content is obtained!

MongoDB is waiting for a collection, containing at least one documents (records), to be formed before the database is constructed (and collection).

You can also search for these topics, python mongodb create database if not exists, database and users to create a python mangodb, define the collection of database in python mangodb, define the default value to create database using python mangodb, python list the database in python mangodb.

Check if Database Exists

You should create a collection and building the document before you check that a database exists.

If this is your first time creating a database then the name of database will not be displayed until it get atleast a document in it.

The list_database_names() method is used to return all available database names from mongodb, which contains atleast one document.

Exmaple :- Return all database names :

import pymongo
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
x = myclient.list_database_names()

Output :-

['admin', 'local', 'mydatabase']

Note:- In our case, We have created a collection and added few documents on it.

You can also search for these topics, python check if database exists and not empty, check the database existing argument in python mangodb, exists and create the python database, check python mangodb database exists before opening, available elements and values for check existing of python mango db database, Example for Check if Database Exists in python mangodb.