Book Image

MongoDB Cookbook - Second Edition - Second Edition

By : Amol Nayak
Book Image

MongoDB Cookbook - Second Edition - Second Edition

By: Amol Nayak

Overview of this book

MongoDB is a high-performance and feature-rich NoSQL database that forms the backbone of the systems that power many different organizations – it’s easy to see why it’s the most popular NoSQL database on the market. Packed with many features that have become essential for many different types of software professionals and incredibly easy to use, this cookbook contains many solutions to the everyday challenges of MongoDB, as well as guidance on effective techniques to extend your skills and capabilities. This book starts with how to initialize the server in three different modes with various configurations. You will then be introduced to programming language drivers in both Java and Python. A new feature in MongoDB 3 is that you can connect to a single node using Python, set to make MongoDB even more popular with anyone working with Python. You will then learn a range of further topics including advanced query operations, monitoring and backup using MMS, as well as some very useful administration recipes including SCRAM-SHA-1 Authentication. Beyond that, you will also find recipes on cloud deployment, including guidance on how to work with Docker containers alongside MongoDB, integrating the database with Hadoop, and tips for improving developer productivity. Created as both an accessible tutorial and an easy to use resource, on hand whenever you need to solve a problem, MongoDB Cookbook will help you handle everything from administration to automation with MongoDB more effectively than ever before.
Table of Contents (17 chapters)
MongoDB Cookbook Second Edition
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

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…

  1. 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
    
  2. Install the latest PyMongo driver using pip:

    > pip install pymongo
    
  3. 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()
  4. 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.