Python with MongoDB NoSQL database is a very good combination in handling big data. In this article, we will create a database and perform some CRUD (Create, Read, Update, and Delete) operations in the database using Python language. This article assumes that you have some basic knowledge of MongoDB database and its operations.
The pymongo module
The PyMongo distribution contains tools for interacting with MongoDB database from Python. It allows you to perform CRUD operations and more complex queries against the database. You can also mimic the shell-like syntax on the command line or in your scripts.
PyMongo can be installed using pip. Execute the following command to install Pymongo:
pip install pymongo
Create Database in MongoDB
The first step is to create a MongoDB database where we will create collections of documents. We can create a new database using the PyMongo driver by connecting to the MongoDB database server and calling the MongoClient() class. MongoClient() uses the MongoDB URI to establish a connection to the database server. The URI can be in the form of a string that specifies the host, port, and database name to connect to.
from pymongo import MongoClient # MongoDB Connection client = MongoClient("<url>") # Creating the database db = client["<database_name>"]
Note: Replace the url with the MongoDB database url and database_name with the name of the database that you want to create.
Connecting to the MongoDB database server
# MongoDB Connection client = MongoClient("<url>")
First, we need to connect to the MongoDB server. MongoClient connects to the default MongoDB port (27017) on localhost by default, so in the code above, we did not need to specify the port, but you can include it as part of the URL.
Creating the database in MongoDB
# Creating the database db = client["<database_name>"]
To create a new database in MongoDB using PyMongo, you can simply reference the database’s name as a key on the connected MongoClient instance. The above code creates a new database named “database_name” in MongoDB.
from pymongo import MongoClient # MongoDB Connection client = MongoClient('mongodb://localhost:27017/') # Creating the database db = client.database_name # Displaying the available databases print(client.list_database_names())
['admin', 'config', 'database_name', 'local']
The above code snippet displays the available databases on your MongoDB server.
In the example above, we imported the MongoClient class from the PyMongo module, created an instance of the client by passing a URI string containing the address of the MongoDB server and the port number, and then specified the name of the database we want to create as a string. This is equivalent to the following command in the MongoDB shell:
> use database_name
Creating MongoDB database is simple using PyMongo as its driver. We need to establish a connection to a MongoDB server and pass the name of the database. After that, we can create collections and perform CRUD operations.