How to setup MongoDB with Jupyter Notebook
Tags: beginners, python, database, mongodb
Published: 2022-10-15 13:11:29

I have to conclusion how to setup MongoDB (NoSQL) with Jupyter Notebook by summary step like this.

**First step**, Install [python 3.9.1] (https://www.python.org/downloads/release/python-391/) for use on python, install `$ pip install pymongo`.

**Second step**, Install [homebrew](https://brew.sh/) with `$ /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"`

**Third step**, Install [Jupyter Notebook](https://jupyter.org/install) on Windows, MacOS or Linux and try to install `$ pip install notebook` in terminal and run `$ jupyter notebook`

**Fourth step**, Install MongoDB Community Edition on macOS [mongoDB](https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-os-x/) and [MongoDB Compass](https://www.mongodb.com/try/download/compass)

**install** `$ brew tap mongodb/brew` and `$ brew install mongodb-community`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dm9xck3uas4coz8ob0uu.png)

**Install MongoDB on Ubuntu**

`$ sudo apt update`

`$ sudo apt install wget curl gnupg2 software-properties-common apt-transport-https ca-certificates lsb-release`

`$ curl -fsSL https://www.mongodb.org/static/pgp/server-6.0.asc|sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/mongodb-6.gpg`

`$ echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list`

`$ wget http://archive.ubuntu.com/ubuntu/pool/main/o/openssl/libssl1.1_1.1.1f-1ubuntu2.16_amd64.deb`

`$ sudo dpkg -i ./libssl1.1_1.1.1f-1ubuntu2.16_amd64.deb`

`$ sudo apt update`

`$ sudo apt install mongodb-org`

`$ sudo systemctl enable --now mongod`

**_Checking config of mongod.conf on development mode_**

`$ sudo vi /etc/mongod.conf`

```
#add this line
    security:
          authorization: enabled
# network interfaces
    net:
      port: 27017
      bindIp: 0.0.0.0  # Change to global
```

Restart service again with `$ sudo service mongod restart`

**Create the “db” directory** where MongoDB stores its database by `$ mkdir -p /data/db`

**Make sure that the directory has the previlage to read and write from the directory by using chown** (change owner) with `$ chown -R 'id -un'/data/db`

**Start MongoDB command :** `$ brew services start mongodb-community`

**Using** `$ ps aux | grep -v grep |grep mongod`, allow us to verify that MongoDB is running. You should see the current ststus of your mongod process.

**_On Ubuntu, You can followup setup directory like this._**
`$ sudo systemctl stop mongod.service`
`$ sudo mkdir -p /newdata/mongo`
`$ sudo chown -R mongodb:mongodb  /newdata/mongo`
`$ sudo rsync -av /var/lib/mongodb  /newdata/mongo`
`$ sudo mv /var/lib/mongodb /var/lib/mongodb.bak`
`$ sudo ln -s /newdata/mongo /var/lib/mongodb`
`$ sudo systemctl daemon-reload`
`$ sudo systemctl start mongod`

**Five step**, Install **mongosh** for start [mongosh](https://www.mongodb.com/docs/mongodb-shell/connect/#std-label-mdb-shell-connect), [MongoDB Shell](https://www.mongodb.com/docs/mongodb-shell/#mongodb-binary-bin.mongosh) and create role user on database

```
$ mongosh
    test> use admin
    test> db.createUser({user: "myUserAdmin", pwd: "abc123",  roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]})
    test> exit
$ mongosh -u mongdbuser -p --authenticationDatabase admin
Enter password: ********
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xiy4b8wyqzj1zbg5m1x6.png)

**write the code below**

```python
import pymongo
from pymongo import MongoClient

username='myUserAdmin'
password='abc123'
client = MongoClient('mongodb://%s:%s@127.0.0.1' % (username, password))
db=client['mongotestdb']

my_collection = db["patient_data"]

patient_record = {
   "Name": "Maureen Skinner",
   "Age": 87,
   "Sex": "F",
   "Blood pressure": [{"sys": 156}, {"dia": 82}],
   "Heart rate": 82
}

my_collection.insert_one(patient_record)

for item in my_collection.find():
    print(item)
```

**Result on MongoDB Compass**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bll58vadkgtr3bil1q1n.png)

**Stop MongoDB command :** `$ brew services stop mongodb-community`

**Reference:** [MongoDB tutorial](https://www.geeksforgeeks.org/mongodb-tutorial/), [mongosh](https://www.youtube.com/watch?v=ofme2o29ngU), [Building Data Pipeline | Spotify - Jupyter Notebook - MongoDB](https://www.youtube.com/watch?v=hJ1RuXvHOe0), [Connecting MongoDB to Jupyter Notebook](https://medium.com/@pragya_paudyal/connecting-mongodb-to-jupyter-notebook-e3f636a85830), [Example Query NoSQL](https://towardsdatascience.com/8-examples-to-query-a-nosql-database-fc3dd1c9a8c), [Setting user account](https://medium.com/@haxzie/getting-started-with-mongodb-setting-up-admin-and-user-accounts-4fdd33687741), [Using MongoDB in python](https://towardsdatascience.com/using-mongo-databases-in-python-e93bc3b6ff5f), [Install Jupyter Notebook on Ubuntu](https://linuxhint.com/install-jupyter-notebook-on-ubuntu-20-04/)