Python MongoDB - Create Database


Advertisements

Unlike other databases, MongoDB does not provide separate command to create a database.

In general, the use command is used to select/switch to the specific database. This command initially verifies whether the database we specify exists, if so, it connects to it. If the database, we specify with the use command doesn’t exist a new database will be created.

Therefore, you can create a database in MongoDB using the Use command.

Syntax

Basic syntax of use DATABASE statement is as follows −

use DATABASE_NAME

Example

Following command creates a database named in mydb.

>use mydb
switched to db mydb

You can verify your creation by using the db command, this displays the current database.

>db
mydb

Creating Database Using Python

To connect to MongoDB using pymongo, you need to import and create a MongoClient, then you can directly access the database you need to create in attribute passion.

Example

Following example creates a database in MangoDB.

from pymongo import MongoClient

#Creating a pymongo client
client = MongoClient('localhost', 27017)

#Getting the database instance
db = client['mydb']
print("Database created........")

#Verification
print("List of databases after creating new one")
print(client.list_database_names())

Output

Database created........
List of databases after creating new one:
['admin', 'config', 'local', 'mydb']

You can also specify the port and host names while creating a MongoClient and can access the databases in dictionary style.

Example

from pymongo import MongoClient

#Creating a pymongo client
client = MongoClient('localhost', 27017)

#Getting the database instance
db = client['mydb']
print("Database created........")

Output

Database created........

Useful Video Courses


Video

Python Online Training

Most Popular

187 Lectures 17.5 hours

Malhar Lathkar

Video

Python Essentials Online Training

55 Lectures 8 hours

Arnab Chakraborty

Video

Learn Python Programming in 100 Easy Steps

136 Lectures 11 hours

In28Minutes Official

Video

Python with Data Science

75 Lectures 13 hours

Eduonix Learning Solutions

Video

Python 3 from scratch to become a developer in demand

70 Lectures 8.5 hours

Lets Kode It

Video

Python Data Science basics with Numpy, Pandas and Matplotlib

63 Lectures 6 hours

Abhilash Nelson

Advertisements