September 2011
Intermediate to advanced
138 pages
1h 44m
English
Connection objects themselves are not all that frequently used when working with MongoDB in Python. Typically you create one once, and then forget about it. This is because most of the real interaction happens with Database and Collection objects. Connection objects are just a way to get a handle on your first Databse object. In fact, even if you lose reference to the Connection object, you can always get it back because Database objects have a reference to the Connection object.
Getting a Database object is easy once you have a Connection instance. You simply need to know the name of the database, and the username and password to access it if you are using authorization on it.
""" An example of how to get a Python handle to a MongoDB database """
import sys
from pymongo import Connection
from pymongo.errors import ConnectionFailure
def main():
""" Connect to MongoDB """
try:
c = Connection(host="localhost", port=27017)
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()Read now
Unlock full access