Pymongo is a Python to be able to connect to a database MongoDB. In this example we are going to see how we can create the first program that connects from Python a MongoDB. To do this we are going to create hello world with Pymongo.
The first thing will be to install Pymongo. To do this we are going to use the pip command.
pip install pymongo
or
python -m pip install pymongo
The object that the Pymongo library offers us to connect to MongoDB is the MongoClient, so the beginning of our program will import said object.
from pymongo import MongoClient
If we use a default connection and have MongoDB installed on our machine we will simply instantiate the object.
client = MongoClient()
If the MongoDB database is on another machine or has a username/password (something quite normal and recommended) we must pass the connection URL as a parameter.
client = MongoClient('mongodb://user:pass@srvidor:27017/')
Now that we are connected to the server we are going to choose which database we want to use. If, for example, we had a database called users, we would write the following:
db = client.users
The next thing will be to choose the collection on which we want to iterate. If our collection is a list we will have to write the following code:
list = db.list
We see that we have put the database followed by the collection name.
The syntax of Pymongo is very similar to that used in the MongoDB. Which makes it very easy to learn and write.
If we want to retrieve the first document in the collection we have the .find_one() method
print users.find_one()
When we print it on the screen we will obtain the JSON corresponding to the first document.
With these few lines of code we have built our hello world program with Pymongo that allows us to create a program Python to access MongoDB.
