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.

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"]
Copy

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

Output

PyMongo – How to Create MongoDB Database?

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.

Related Tutorials

Code copied to clipboard successfully 👍