How do I create a new database in MongoDB using PyMongo?

Can I create a new database simply by connecting to the MongoDB server, or is there another way to create it using Python? If so, how is this done?


MongoDB creates databases and collections automatically for you if they don't exist already.

For using python library with MongoDB, check out this documentation.

Warning: the example is based on Pymongo 2.1. If you're using Pymongo 3.4, check this doc.

from pymongo import Connection
connection = Connection()
db = connection['test-database']
collection = db['test-collection']

So here you can use any name for database and collection.


This is Mongodb 3.4 Version:

from pymongo import MongoClient
client = MongoClient()
db = client.primer
coll = db.dataset

neither the database nor the collection are created until you attempt to write a document.

Document: Python Driver (PyMongo)