Create MongoDB Database - PyMongo - Examples
Create a Database using PyMongo
To create a Database in MongDB from Python using PyMongo,
- Create a client to the MongoDB instance.
- Provide the name of the database to the client. It returns a reference to the Database.
- Now you can use this database reference to modify your collections or documents.
Examples
1. Create MongoDB Database whose name is "organisation"
In the following program, we created a database named organisation.
Python Program
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
#use database named "organisation"
mydb = myclient["organisation"]
Note: Database is actually created when there is content in the database. So, only when there is atleast one document inside the database, you could see that the database is created when you run list_databases() function. In the following example, we have created the database, inserted a document and then listed the databases.
Python Program
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
#use database named "organisation"
mydb = myclient["organisation"]
#use collection named "developers"
mycol = mydb["developers"]
#a document
developer = { "name": "Lini", "address": "Sweden" }
#insert a document to the collection
x = mycol.insert_one(developer)
#list the databases
for db in myclient.list_databases():
print(db)
Output
In the above screenshot, we have run a python program to list the databases present in MongoDB instance. Then we ran the above python program, where we created a mongodb database and created a document in it.
Summary
In this PyMongo Tutorial, we learned how to create a MongoDB database, with examples.