Skip to content
Sign upLog in
← Back to Community

[MongoDB] How to tell how many burritos 🌯 or tacos 🌮 are in a database with mongoDB

Profile icon
InvisibleOneHacker

Using mongo DB with python

I know this is a repost but I accidently deleted it which was pretty stupid of me

Step one: Make a mongoDB database (atlas)

First got to mongodb.com

Screen Shot 2021-01-26 at 11.21.28 AM

Next create a user:

Screen Shot 2021-01-26 at 11.22.53 AM

You will then need to go to your email and confirm it, and sign in to your database. You should open up a screen that looks like this:

Screen Shot 2021-01-26 at 11.24.20 AM

Go to Database Access

Screen Shot 2021-01-26 at 11.25.07 AM

Click the button to create a database user

Screen Shot 2021-01-26 at 11.25.51 AM

Save it and then go to clusters

Screen Shot 2021-01-26 at 11.26.11 AM

From there create a cluster:

Screen Shot 2021-01-26 at 11.26.41 AM

Choose the free version (free means you don’t have to pay any money)

Screen Shot 2021-01-26 at 11.27.20 AM

Fill out a few details and then you should be good to go. It will take a few minutes for mongo to build your database, and then you should be looking at a screen that looks like this one:

Screen Shot 2021-01-26 at 11.33.57 AM

Click on connect

Screen Shot 2021-01-26 at 11.34.47 AM

Then Allow Access from Anywhere

Screen Shot 2021-01-26 at 11.35.10 AM

Then choose connection method

Screen Shot 2021-01-26 at 11.36.26 AM

Select Connect you application, then select python as the platform and 3.6 as the version.

Screen Shot 2021-01-26 at 11.36.52 AM

It will generate your a link that you can then copy

Screen Shot 2021-01-26 at 11.37.35 AM

You’ll need this link to connect to your database.
Click close and go back to the main screen.

Click on collections

Screen Shot 2021-01-26 at 11.39.10 AM

Then add my own data

Screen Shot 2021-01-26 at 11.40.00 AM

I created a database called mydatabase and a collection called burrito

Screen Shot 2021-01-26 at 11.40.40 AM

Click create, and then insert document.

Screen Shot 2021-01-26 at 11.40.54 AM

We’ll create a document (basically the same as a dictionary in python) with a key ‘burrito’ and a value of 0. Be sure to set it as an int64 and not a string.

Screen Shot 2021-01-26 at 11.41.23 AM

Now you should be able to see you document inside of your collection. Now we move to the actual programming part of it.

Screen Shot 2021-01-26 at 11.41.48 AM

Step Two: Connecting to the database using python

Alright, the first thing we need to do in our python repl is connect to the database. To use mongo db we need to import pymongo

We will also need to import os

Then we connect to the mongoDB like this:

client = pymongo.MongoClient("mongodb+srv://test_user:[email protected]/mydatabase?retryWrites=true&w=majority") #connect to the mongodb using the url it gave us #change <password> to your password and <database> to the name of yoru database mydb = client["mydatabase"] #this selects our database from our client which could have multiple databases if we wanted it to mycol = mydb['burrito'] # this selects the collection from the multiple collections that might be in a database

If you run this code, you might get an error saying that to use mongodb+srv you need to have dnspython installed. We can fix this be either putting os.system(‘pip install dnspython right after our imports, or we can go to the shell part of our repl and type pip install dnspython

Now to get data from our database. There are two ways we can do this, we can use find_one() which will return the first document in our collection, or we can use find(query) to find one out of many documents in the collection. Since we only have one document in the collection, we can just use find_one() as it is more simple.

x = mycol.find_one() #this will give us the first document in our collection print(x['burrito']) #this will the value of zero from our document

We can also insert new values into a document, like this:

query = { "burrito" : x['burrito']} # we need to use this to find any document who's value matches this new_val = { "$set" : { "burrito" : x['burrito'] + 1 } } #this will be the new value mycol.update_one(query, new_val) # the the value of 'burrito' will be 1 more then it was before

Now we can put it all together:

import pymongo import os os.system('pip install dnspython') client = pymongo.MongoClient("mongodb+srv://test_user:[email protected]/mydatabase?retryWrites=true&w=majority") mydb = client["mydatabase"] mycol = mydb['burrito'] while True: x = mycol.find_one() os.system('clear') print("There are: " + str(x['burrito']) + " burritos") i = input() if i.lower() == 'burrito': query = { "burrito" : x['burrito']} new_val = { "$set" : { "burrito" : x['burrito'] + 1 } } mycol.update_one(query, new_val)

And there you go, a system to tell how many times somebody has typed burrito in.
But what if we also want to know how many times someone types taco in?
Well all we have to do is make another collection. We can do that by typing:
mytaco_collection = mydb[‘taco’] which will create a new collection called taco
Now, if you go and look at your collections in you mongoDB manager, you won’t see a collection called taco. That’s because it will not actually create a new collection unless you put any data into it. We can add a document to this collection using insert_one, which takes a dictionary, like this:

my_data = { 'taco' : 0, } tacos = mytaco_collection.insert_one(my_data)

Now if you go and look in you MongoDB, you’ll see that there is another collection, taco

Screen Shot 2021-01-26 at 12.11.18 PM

We can now remove this piece of code (or else when we run the repl it will constantly insert a new document.
Now let’s add some code to our while True loop

while True: x = mycol.find_one() #new code here t = mytaco_collection.find_one() os.system('clear') print("There are: " + str(x['burrito']) + " burritos") # and here print("There are: " + str(t['taco']) + " Tacos") i = input() if i.lower() == 'burrito': query = { "burrito" : x['burrito']} new_val = { "$set" : { "burrito" : x['burrito'] + 1 } } mycol.update_one(query, new_val) # and new code here elif i.lower() == 'taco': query = { "taco" : t['taco'] } new_val = { "$set" : { "taco" : t["taco"] + 1 } } mytaco_collection.update_one(query, new_val)

Now we can see how many times the word burrito and taco have been typed in. Pretty cool right?

full repl attached below

https://repl.it/@InvisibleOne/MongoDB#main.py

Voters
Profile icon
DwellerIgor
Profile icon
Yoplayer1py
Profile icon
IntellectualGuy
Profile icon
Smart0ne
Profile icon
TsunamiOrSumth
Profile icon
EpicGamer007
Profile icon
InvisibleOne
Comments
hotnewtop
Profile icon
BrendaStarks

Thank you. I have never tried it before but after reading your post. I will surely try it. But before that I want to visit https://www.topwritersreview.com/ here to find the best essay writer for my friend who is not good at writing an essay assignments.

Profile icon
VulcanWM

the code isn't up to date that's why it's showing an error.
add import dns in the code instead of the pip installing

Profile icon
InvisibleOne

Yeah I should fix that

@VulcanWM

Profile icon
VulcanWM

great, nice tutorial tho!

@InvisibleOne

Profile icon
Smart0ne

Another question: When I click Connect, Allow Access from Everywhere, and the Choose Connection Settings, there is a red X mark beside "Setup connection security".

Profile icon
InvisibleOne

That's fine, unless you are using a fixed IP that you can't narrow down that security anyways

@Smart0ne

Profile icon
Smart0ne

@InvisibleOne
:omigthy: Thank you! It's working now! The issue was that I didn't know that 0.0.0.0/0 was a "wild card" IP address (maybe I'm still wrong idk), so I deleted that and entered my current IP address.

Profile icon
InvisibleOne

Great, let me know if you run into any other problems and I can try and help

@Smart0ne

Profile icon
Smart0ne

Since I'm using this tutorial, I have an error. I connected to the my database by

client = pymongo.MongoClient("mongodb+srv://Smart0ne:<password>@cluster0.ha7az.mongodb.net/accounts?retryWrites=true&w=majority")

where is replaced by my password. After, I have

db = client["accounts"]

and then

col = db["accounts"]

But when this code is executed:

x = col.find_one()

I get this error

Traceback (most recent call last): File "main.py", line 13, in <module> x = col.find_one() File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/collection.py", line 1319, in find_one for result in cursor.limit(-1): File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/cursor.py", line 1207, in next if len(self.__data) or self._refresh(): File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/cursor.py", line 1100, in _refresh self.__session = self.__collection.database.client._ensure_session() File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1816, in _ensure_session return self.__start_session(True, causal_consistency=False) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1766, in __start_session server_session = self._get_server_session() File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1802, in _get_server_session return self._topology.get_server_session() File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/topology.py", line 490, in get_server_session self._select_servers_loop( File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/topology.py", line 215, in _select_servers_loop raise ServerSelectionTimeoutError( pymongo.errors.ServerSelectionTimeoutError: connection closed,connection closed,connection closed, Timeout: 30s, Topology Description: <TopologyDescription id: 601aa99a7cd0ded43fa8a0a6, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('cluster0-shard-00-00.ha7az.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('connection closed')>, <ServerDescription ('cluster0-shard-00-01.ha7az.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('connection closed')>, <ServerDescription ('cluster0-shard-00-02.ha7az.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('connection closed')>]>

I checked my database, and I have a document in the collection. I'm not sure what went wrong. Could you help?

@InvisibleOne

Profile icon
InvisibleOne

Hmm, have you tried running 'pip install dnspython' in the shell?

@Smart0ne

Profile icon
Smart0ne

@InvisibleOne
Yes, I have. It gives me the same error.

Profile icon
InvisibleOne

Could you invite me to the repl?

@Smart0ne

Profile icon
Smart0ne

@InvisibleOne
Alright.

Profile icon
DavidCZ2051

@Smart0ne
Hi, have you fixed this?

Profile icon
Whippingdot

me no understand anything what is this used por?

Profile icon
InvisibleOne

It's just a database, you can use it to save pretty much whatever you want, for example if you made a game and you wanted the ability for players to sign in and have all their 'stuff' saved. You could create a document with a username, password, and a list of items that the user has. Then when they sign in query the database to return any document that matches that username and password.

@Whippingdot

Profile icon
Whippingdot

Ok thanks also can you check out my tutorial in the new area

@InvisibleOne

Profile icon
InvisibleOne

np don't advertise!

@Whippingdot

Profile icon
Whippingdot

i know that is why in strikthru

@InvisibleOne

Profile icon
TsunamiOrSumth

Ok well how come my burrito just popped out of my hands after you deleted the post
>:( give me another

Profile icon
InvisibleOne

Sorry, here you go:

🌯

@TsunamiOrSumth