Skip to content

MongoDB and PyMongo Easy installation and Tutorial for Debian based OSes- 2020 -HOXFRAMEWORK

Posted in VIDEOS

Hello everyone and thank you for visiting.

Today we will be installing mongodb on debian / debian based OS and then we will go trough on how to install PyMongo and approach the mongoDB trough python.
I will showcase usage examples and some troubleshooting, so let’s get started.


Firstly run :

>sudo apt-get install gnupg

To make sure gnupg is installed on your system

>wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -

To import the public key , then 

>echo "deb http://repo.mongodb.org/apt/debian buster/mongodb-org/4.4 main" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list

In order to add the repository to APT, after that run 

>sudo apt-get update

Lastly, if it already isnt installed - install mongodb : 

> sudo apt-get install -y mongodb-org

Next you have to run mongodb service "mongod".

>sudo systemctl start mongod

You can add it to startup too if you want

>sudo systemctl enable mongod

Lastly run the mongo db itself using the command "mongo" in the terminal:

>mongo

COMMANDS USED FOR MONGODB USAGE:

>show dbs
to show databases
>use <db>
to use the database <db>
>show collections
to show collections (similar to tables in sql)
>db.collectionName.insertOne({"name":"Joe"});
to insert the entry with key "name" and value "Joe" - using insertOne only allows us to insert one entry, if you want to insert more use "insertMany".
>db.collectionName.find()
to find all. You can append ".pretty()" to make the output nicer.


PYTHON CODE USED:

import pymongo
from pymongo import MongoClient

#define the client and connection to be hosted at localhost at port 27017
client = MongoClient("localhost", 27017)
db = client["mytestdb"]
#define database to use

db_list = client.list_database_names()
print(db_list)
#lists database names

#list collections:
coll_list = db.list_collection_names()
print(coll_list)

#lastly - print out all the data in the collection:
finder = collection.find({})
for k in finder:
	print(k)


And that's it ! Thank you so much for visiting and have a nice day :).