Databases Reference
In-Depth Information
Real-Time Analytics: Python
The Python driver for MongoDB is called PyMongo . In this section, we'll use PyMongo
to implement some real-time tracking of metrics for a web application. The most up-
to-date documentation on PyMongo is available at http://api.mongodb.org/python .
Installing PyMongo
PyMongo is available in the Python Package Index and can be installed using
easy_install ( http://pypi.python.org/pypi/setuptools ) :
$ easy_install pymongo
Searching for pymongo
Reading http://pypi.python.org/simple/pymongo/
Reading http://github.com/mongodb/mongo-python-driver
Best match: pymongo 1.6
Downloading ...
Processing pymongo-1.6-py2.6-macosx-10.6-x86_64.egg
Moving ...
Adding pymongo 1.6 to easy-install.pth file
Installed ...
Processing dependencies for pymongo
Finished processing dependencies for pymongo
This will install PyMongo and will attempt to install an optional C extension as well.
If the C extension fails to build or install, everything will continue to work, but per-
formance will suffer. An error message will be printed during install in that case.
As an alternative to easy_install , PyMongo can also be installed by running python
setup.py install from a source checkout.
Using PyMongo
We use the pymongo.connection.Connection class to connect to a MongoDB server. Here
we create a new Connection and use attribute-style access to get the analytics database:
from pymongo import Connection
db = Connection().analytics
The rest of the API for PyMongo is similar to the API of the MongoDB shell; like the
Ruby driver, PyMongo uses underscore_naming instead of camelCase, however.
Documents are represented using dictionaries in PyMongo, so to insert and retrieve the
document {"a" : [1, 2, 3]} , we do the following:
db.test.insert({"a": [1, 2, 3]})
db.test.find_one()
Dictionaries in Python are unordered, so PyMongo provides an ordered subclass of
dict , pymongo.son.SON . In most places where ordering is required, PyMongo provides
 
Search WWH ::




Custom Search