Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
MongoDB Cookbook - Second Edition

You're reading from   MongoDB Cookbook - Second Edition Modern Database Management Made Easy

Arrow left icon
Product type Paperback
Published in Jan 2016
Publisher
ISBN-13 9781785289989
Length 370 pages
Edition 2nd Edition
Tools
Arrow right icon
Authors (2):
Arrow left icon
Amol Nayak Amol Nayak
Author Profile Icon Amol Nayak
Amol Nayak
Cyrus Dasadia Cyrus Dasadia
Author Profile Icon Cyrus Dasadia
Cyrus Dasadia
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Installing and Starting the Server 2. Command-line Operations and Indexes FREE CHAPTER 3. Programming Language Drivers 4. Administration 5. Advanced Operations 6. Monitoring and Backups 7. Deploying MongoDB on the Cloud 8. Integration with Hadoop 9. Open Source and Proprietary Tools A. Concepts for Reference 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.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image