Thursday, November 7, 2013

Connecting to a MongoDB database from a Python script

Now that we have pymongo setup, we will connect to the MongoDB database (mydb) from a python script. The source of the script is from the "MongoDB and Python Patterns and processes for the popular document-oriented database By Niall O'Higgins"

#!/usr/bin/python
import sys
from pymongo import Connection
from pymongo.errors import ConnectionFailure

def main():
    """ Connect to MongoDB """
    try:
        c = Connection(host="localhost", port=27017)
        print ("Connected successfully")
    except ConnectionFailure, e:
        sys.stderr.write("Could not connect to MongoDB: %s" % e)
        sys.exit(1)
    # Get a Database handle to a database named "mydb"
    dbh = c["mydb"]
       
    # Demonstrate the db.connection property to retrieve a reference to the
    # Connection object should it go out of scope. In most cases, keeping a
    # reference to the Database object for the lifetime of your program should
    # be sufficient.

    assert dbh.connection == c
    print "Successfully set up a database handle"


if __name__ == "__main__":
    main()

Output on executing the script test.py
Here is what I did to install the pymongo module on my system.

[root@isvx7 ~]# ./test.py
Connected successfully
Successfully set up a database handle

Message on the mongod console:

Thu Nov  7 12:48:56 [initandlisten] connection accepted from 127.0.0.1:33804 #4 (1 connection now open)
Thu Nov  7 12:48:56 [conn4] end connection 127.0.0.1:33804 (0 connections now open)

No comments: