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 :-
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).
Related Links
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()
print(x)
Output :-
Note:- In our case, We have created a collection and added few documents on it.
Related Links