Connecting MongoDB to Jupyter Notebook
MongoDB is one of the most famous NoSql databases. It is an open-source database. The simple meaning of the NoSql database is a non-relational database. i.e., It doesn’t include the specific structure of databases such as tables and all like the relational database. So, you can design the schemas without any restrictions.
Jupyter Notebook is also an open-source web application that allows users to create and share documents that contain live code, equations, visualizations, and narrative text. By using the Jupyter notebook, programmers can make the code clean and debug and execute it step by step. We can use the 40+ different languages with the Jupyter notebook, and among the most popular is Python.
In this tutorial, we will connect the MongoDb to the Jupyter Notebook in the python language.
Now, follow the below steps to start the MongoDB server on localhost and connect it to the Jupyter Notebooks.
Step 1: After installing the MongoDB on your Windows, start the MongoDB server by entering the below command to the command prompt.
You will see the following logs on your terminal. Also, at the end of the records, you can see that server has been started on the 27017 port.
Step 2: Now, open the other command prompt window and write the below command to start the mongo shell. Ensure that you haven’t closed the first command prompt window and the server is still running without any error.
You will see the following logs on your terminal.
Step 3: You can enter the below commands to see your default databases.
On the terminal, you will see the following outputs. Maybe the names of your databases can be different.
Step 4: Launch Jupyter NoteBook and create a new Jupyter Notebook file.
Step 5: We will use the python PyMongo module to connect the Jupyter Notebook with the MongoDB localhost. So, write the below code into the NoteBook cell.
!pip install pymongo
Note: Users can run the Jupyter NoteBook cell by pressing the Shift + Enter.
Step 6: In the next cell, import the PyMongo module and execute the cell. If the cell runs without any error, PyMongo module is successfully installed.
from pymongo import MongoClient
Step 7: Next, connect the MongoDB database using the below line of code. Don’t forget to execute the cell of the Jupyter Notebooks.
client = MongoClient(“localhost”, 27017)
Step 8: Now, add the below code to the next cell and execute it to fetch any collection from the database. Here, we are fetching the ‘test‘ collection.
db = client[‘test’]
You will see the following logs on your NoteBook file.
You have connected the MongoDB database with the Jupyter NoteBook. Now, you can perform the same operation from Jupyter NoteBook that you can perform from the Mongo shell.