Learn to Code via Tutorials on Repl.it!

← Back to all posts
[100 CYCLE SPECIAL] How to use MongoDB PYTHON
CoolJames1610 (618)

Hey guys and welcome to this tutorial

bruh why am i doing it like a youtube video XD

Before we start, thanks to all who have upvoted anything of mine (projects, comments etc). Go upvote the below if you already haven't XD
PyTube
GLOBAL REPL COUNTER

WELCOME TO THE MONGODB TUTORIAL!

First, go to mongodb.com

and create an account!

Then, after you have created your account, it will show you three plans. I would recommend getting the FREE one for testing purposes and it means you don't have to pay

After that, you select which provider you want and where that server-cloud thingy is. The star is used for recommended ones. Then name your cluster!

IG MEANS IGNORE Because if you change them, it changes to a paid plan :(

Then, MongoDB will start making your cluster. It takes a few minutes. So while you are waiting you can play PyTube or something XD

Once it has finished, it should look like this. Then you press the connect button

It will then ask you for some info. At first, use your own IP and create a user. You will need to remember your password!

Once you have filled in the details, it is TIME TO CONNECT WITH PYTHON - (there are lots of other languages you can use but I only know python...)

Select connect your application

Since repl uses the latest version of every language (i think), choose python and go to 3.6 or later

Click show full driver and copy the contents! You can now press close... IT IS TIME FOR PYTHON!

Oh and before you go to python, go to Network Access, add a new IP ADDRESS and allow ACCESS FROM ANYWHERE, then wait until MongoDB has added that :) :D


NOW IT IS TIME FOR PYTHON XD

We need to import pymongo and dns

import pymongo, dns 

Then, paste your connection string that you pasted from MongoDB

This is mine -->

client = pymongo.MongoClient("mongodb+srv://Example:[email protected]/test?retryWrites=true&w=majority") 

To create a database, you can use either:

db = client.Example

or:

db = client["Example"]

<-- Use this way if you want the user to be able to create their own database with their own name (look in project below for example)

And it is exactly the same for the collection!

 mycol = db.Example

or:

 mycol = db["Example"]

<-- Again use this way for the example stated above ;)

To add documents to your database, use a dictionary inside a list:

 documents = [{"Name": "CoolJames", "Upvote?": True, "Cycles?": 100}]

MongoDB automatically knows that "Name" contains a string, "Upvote? contains a boolean and that "Cycles?" contains an integer!

Then do:

mycol.insert_many(documents)

CONGRATS! YOU HAVE SUCCESSFULLY EXPORTED DATA INTO MONGODB

If you have done it right, it should look something like this:

But what if I want to get my data from my database?

To get your data, use the connection string and assign db and mycol to the same name in the database. (In my case, db = client.CoolJames and mycol = db.CoolJames)

You can still use client[name] and db[name]. Look in project for example but they have to equal what the database and collection are named in MongoDB

To collect the data, we use .find

You can either find one value or find many

To find many, you would loop each time and do the converting and to find one, you would only need to do it once. Look in project for more detail.

I would use loop once if I'm trying to get user info that is in a separate database (SEE PYTUBE)

I would use loop until... if I want to get all the data from a collection (SEE GLOBAL REPL COUNTER)

Now the next is how to assign variables to the data that you have collected. This took me a few days to find out (by going on several websites and piecing the code together)

Now we want x in a string so we can do x = "'" str(x) + "'" and that would enclose x in a string.

We then import re and use .sub to remove the braces and any other special characters that we don't want.

We then enclose it in a list

lst = [x]

and use the function convert (d = convert(lst) -->

def convert(lst): 
return ' '.join(lst).split()

This puts each word as a separate entity in a list and then you can easily assign each variable to an index in the list e.g.

name = d[1]
upvote = d[3]
cycles = d[5]

And there you have it! You have exported data to the database, then collected it back and assigned the data into variables that you can use! This is why you are able to get your data easily in PyTube and use them!

Woweeee
This has taken SO long to write out
an upvote would be very helpful XD
ahhh im so tired now

<3 MongoDB

Project below helps a bit more!

SHOUTOUT TO: @Zuhdi28, @NoelBryan

BTW @amasad commented :O :O :O

There are loads more things you can do with MongoDB, click here for more information!

Thanks for reading!

@CoolJames1610

Commentshotnewtop
CoolJames1610 (618)

OH WOW THANKS OH WOW OH WOW THANKS :D THANKS OOOHHHH THANKS! @amasad

coderash (277)

WOW thx, i used this in a python competition for a leaderboard, fingers crossed i win because of it !

CoolJames1610 (618)

ah cool, where is the comp? @coderash

SwaroopBappanad (39)

@CoolJames1610 Hey, when I put in my database's name instead of 'example', it shows me this:

Any idea how to fix this?

CoolJames1610 (618)

Did you put ur databases password as well?

client = pymongo.MongoClient("mongodb+srv://<USERNAME>:<PASSWORD>@cluster0-wn8ph.mongodb.net/test?retryWrites=true&w=majority")

@SwaroopBappanad

SwaroopBappanad (39)

@CoolJames1610 When I try, It gives me even more errors

DannyIsCoding (663)

Great Tutorial! (You're really good at markdown btw.)

CoolJames1610 (618)

Oh wow thanks! Im not really that good lol. you should have seen it at first @DannyIsCoding

Kopamed (234)

Ummm... is this something im not mongodb enough to understand? Anyway,

BIG

thanks to you for making this 2015-youtube-like tutorial for us lol.
No actually thanks a lot.

JordanDixon1 (352)

One slight problem... The database password is open for all to see!!! If only there was a way to encrypt it but be able to have anyone use the application....

CoolJames1610 (618)

Yeah, that's a problem I had too. I put the password in an .env file but it meant that no one could use it. This is what I do now:

i = open("pass.txt", "r")
username = i.readline()
password = i.readline()
i.close()
client = pymongo.MongoClient("mongodb+srv://" + username + ":" + password + "@cluster0-wn8ph.mongodb.net/test?retryWrites=true&w=majority")

But it's obviously not the best way to do it and when people FORK the project, then they kinda have complete control on what gets added to that database. I'll try and experiment and find out if there is any solution!
@JordanDixon1

JordanDixon1 (352)

@CoolJames1610 At first my mind went to Bcrypt. Unfortunately though, we have to test the password against a string so the password is still visible...

Warhawk947 (519)

@JordanDixon1 usually, if you put the password in a different file and name it something unsuspicious, like gameUtils.py, and put secret=fsjlfsfjisdjfljfklsjflisedjflsjef<insert token thing here>ineedhelpwithmylife, and in your main.py file type from gameUtils.py import secret, no one will notice anything, unless they are like a chad programmer and like to read every single file that you have in your repl

JordanDixon1 (352)

@Warhawk947 That would be me XD but yeah that would work for most of the programmers out there.

Warhawk947 (519)

@JordanDixon1 yeah, i did that once, and it even though it was pretty popular shameless plug no one messed up the database so i guess it works?

JordanDixon1 (352)

@Warhawk947 lol, that's hilarious. I don't feel too safe doing that though. Maybe if we also encoded it in base64 maybe?? And then we could compile using the bash/python command:

python3 -m compileall
Warhawk947 (519)

@JordanDixon1 you can do that? I never knew!

JordanDixon1 (352)

@Warhawk947 Yep. I don't think you can do it in Repl.it but I know you can do it on windows, Linux, or mac (with python of course.) Repl.it doesn't allow you to look at home/runner files or something like that soooo.

JordanDixon1 (352)

@Warhawk947 heres the link on how to decode base64 after decoding it: https://repl.it/@JordanDixon1/PythonB64Pass make sure you go to main.py instead of main.sh. After you understand the way base64 is decoded you could use an encoder and encode the password then you could compile the python file which then you could import as a module.

import main
print(main.password)

or

from main import *
print(password)

And there ya go.

NoelB33 (314)

@Warhawk947 I took your advice and put it in MongoDBUtils.py here https://repl.it/@NoelBryan/MongoDB and then I imported it with like 10 other things so nobody noticies

CoolJames1610 (618)

Your code works perfectly! Well done! :D And wow - for ur connection string XD @NoelBryan

NoelB33 (314)

Thank you! Still, somebody could look through the PyMongoUtls but it works! @CoolJames1610

JordanDixon1 (352)

@NoelBryan If you have python on your computer you could also use base64 encoding, decoding and then compile the file and import it then.

CoolJames1610 (618)

Env wont work if u want people to be able to connect to the database @AmazingMech2418

AmazingMech2418 (900)

@CoolJames1610 Store the link/password in the env file...

NoelB33 (314)

Thanks! I’l make something with this!

CoolJames1610 (618)

No problem! Can't wait to see what you do! @NoelBryan

NoelB33 (314)

Oh this is awesome! I tried it and it worked perfectly first try! Thanks so much! @CoolJames1610

[deleted]

Thanks for mention me and thx for the tutorial!

[deleted]

why do we need to do all this?
we are REPL.IT packages are free!

CoolJames1610 (618)

I cannot do markdown XD

CodingCactus (3013)

@CoolJames1610 lol, why is the whole thing in a quote thing
you need two lines after a quote to unquote

e.g.
> quote

unquote

whereas the below will mean that the whole thing is quoted
> quote
yup, I'm still quoted

CoolJames1610 (618)

oh nice lol idk how to use markdown XD @CodingCactus

CoolJames1610 (618)

Yes I used that all the way through XD @CodingCactus

mwilki7 (1104)

@ShivankChhaya I would recommend reading some of the comments. In particular, some from the CEO.