Using Python to Connect to a MongoDB

This code uses Python to connect to a mongoDB, allowing for print out of the names of all the databases and the names of the collections in a given database, which is in this example is called ‘mydb’.

import pymongo
def mongo_connect():
         conn = pymongo.MongoClient()
         print "Mongo is connected"
         return conn
    except pymongo.errors.ConnectionFailure, e:
         print "Could not connect to MongoDB: %s" % e
conn  = mongo_connect()
print "Database names: %s" % conn.database_names()
db = conn.mydb
coll = db.collection_names()

print "Database name: %s" %
print "Collection names: %s" % coll