PyMongo – How to Create MongoDB Database?

Create a Database using PyMongo

To create a Database in MongDB from Python using PyMongo,

  1. Create a client to the MongoDB instance.
  2. Provide the name of the database to the client. It returns a reference to the Database.
  3. Now you can use this database reference to modify your collections or documents.

Example 1: Create MongoDB Database

In the following program, we created a database named organisation.

import pymongo

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

#use database named "organisation"
mydb = myclient["organisation"]
Run

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.

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)
Run

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.