Connecting to a single node using a Python client
In this recipe, we will connect to a single MongoDB instance using the Python MongoDB driver called PyMongo. With Python's simple syntax and versatility clubbed together with MongoDB, many programmers find that this stack allows faster prototyping and reduced development cycles.
Getting ready
The following are the prerequisites for this recipe:
- Python 2.7.x (although the code is compatible with Python 3.x).
- PyMongo 3.0.1: Python MongoDB driver.
- Python package installer (pip).
- The Mongo server is up and running on localhost and port
27017
. Take a look at the first recipe, Installing single node MongoDB, and start the server.
How to do it…
- Depending on your operating system, install the pip utility, say, on the Ubuntu/Debian system. You can use the following command to install pip:
> apt-get install python-pip
- Install the latest PyMongo driver using pip:
> pip install pymongo
- Lastly, create a new file called
my_client.py
and type in the following code:from __future__ import print_function import pymongo # Connect to server client = pymongo.MongoClient('localhost', 27017) # Select the database testdb = client.test # Drop collection print('Dropping collection person') testdb.person.drop() # Add a person print('Adding a person to collection person') employee = dict(name='Fred', age=30) testdb.person.insert(employee) # Fetch the first entry from collection person = testdb.person.find_one() if person: print('Name: %s, Age: %s' % (person['name'], person['age'])) # Fetch list of all databases print('DB\'s present on the system:') for db in client.database_names(): print(' %s' % db) # Close connection print('Closing client connection') client.close()
- Run the script using the following command:
> python my_client.py
How it works…
We start off by installing the Python MongoDB driver, pymongo, on the system with the help of the pip package manager. In the given Python code, we begin by importing print_function
from the __future__
module to allow compatibility with Python 3.x. Next, we import pymongo so that it can be used in the script.
We instantiate pymongo.MongoClient()
with localhost and 27017
as the mongo server host and port, respectively. In pymongo, we can directly refer to the database and its collection by using the <client>.<database_name>.<collection_name>
convention.
In our recipe, we used the client handler to select the database test simply by referring to client.test
. This returns a database object even if the database does not exist. As a part of this recipe, we drop the collection by calling testdb.person.drop()
, where testdb
is a reference to client.test
and person
is a collection that we wish to drop. For this recipe, we are intentionally dropping the collection so that recurring runs will always yield one record in the collection.
Next, we instantiate a dictionary called employee
with a few values such as name and age. We will now add this entry to our person
collection using the insert_one()
method.
As we now know that there is an entry in the person collection, we will fetch one document using the find_one()
method. This method returns the first document in the collection, depending on the order of documents stored on the disk.
Following this, we also try to get the list of all the databases by calling the get_databases()
method to the client. This method returns a list of database names present on the server. This method may come in handy when you are trying to assert the existence of a database on the server.
Finally, we close the client connection using the close()
method.