[MongoDB] How to tell how many burritos 🌯 or tacos 🌮 are in a database with mongoDB
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
Next create a user:
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:
Go to Database Access
Click the button to create a database user
Save it and then go to clusters
From there create a cluster:
Choose the free version (free means you don’t have to pay any money)
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:
Click on connect
Then Allow Access from Anywhere
Then choose connection method
Select Connect you application, then select python as the platform and 3.6 as the version.
It will generate your a link that you can then copy
You’ll need this link to connect to your database.
Click close and go back to the main screen.
Click on collections
Then add my own data
I created a database called mydatabase
and a collection called burrito
Click create, and then insert document.
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.
Now you should be able to see you document inside of your collection. Now we move to the actual programming part of it.
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
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
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".
That's fine, unless you are using a fixed IP that you can't narrow down that security anyways @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.
Great, let me know if you run into any other problems and I can try and help @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?
Hmm, have you tried running 'pip install dnspython' in the shell? @Smart0ne
@InvisibleOne Yes, I have. It gives me the same error.
Could you invite me to the repl? @Smart0ne
@InvisibleOne Alright.
me no understand anything what is this used por?
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
Ok thanks also can you check out my tutorial in the new area @InvisibleOne
np don't advertise! @Whippingdot
i know that is why in strikthru @InvisibleOne
Ok well how come my burrito just popped out of my hands after you deleted the post
>
:( give me another
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 installingYeah I should fix that @VulcanWM
great, nice tutorial tho! @InvisibleOne