Jul 24, 2013

MongoDB and Python gang thegither!

After a couple of recent posts on MongoLab and Python, I guess it was pretty obvious to mix both :)  The only thing you need to add to your system is PyMongo, the Python driver for MongoDB. If you're using Linux or MacOS, it should be as easy as:

$ sudo easy_install pymongo 
Searching for pymongo 
Best match: pymongo 2.5.2 
Processing pymongo-2.5.2-py2.7-macosx-10.8-intel.egg 
Adding pymongo 2.5.2 to easy-install.pth file 
Using /Library/Python/2.7/site-packages/pymongo-2.5.2-py2.7-macosx-10.8-intel.egg 
Processing dependencies for pymongo 
Finished processing dependencies for pymongo 

Let's try some basic stuff first. You'll just need to use your own username, password, URI, database and collection :)

# Python 2.7
from pymongo import *
 connection = MongoClient("mongodb://USERNAME:PASSWORD@ds051067.mongolab.com:51067/mongolab-test", 51067)
db = connection["mongolab-test"]
c = db["collection1"]
posts = c.find()
for post in posts:
        print (post)

Output:
{u'x': 1.0, u'_id': ObjectId('51e3ce08915082db3df32bf0')}
{u'x': 2.0, u'_id': ObjectId('51e3ce08915082db3df32bf1')}
{u'x': 3.0, u'_id': ObjectId('51e3ce08915082db3df32bf2')}
output removed from brevity
{u'x': 25.0, u'_id': ObjectId('51e3ce08915082db3df32c08')}

OK, now let's go a little bit crazeee:

# Python 2.7 
from pymongo import *
connection = MongoClient("mongodb://USERNAME:PASSWORD@ds051067.mongolab.com:51067/mongolab-test", 51067)
db = connection["mongolab-test"]
c = db["collection1"]
posts = c.find({"x":{"$gte":5,"$lte":10}}).sort([("x",DESCENDING)])
print (c.count())
for post in posts:
        print (post)
        c.insert({"y":post["x"]})
print (c.count())

Output:
25 
{u'x': 10.0, u'_id': ObjectId('51e3ce08915082db3df32bf9')} 
{u'x': 9.0, u'_id': ObjectId('51e3ce08915082db3df32bf8')} 
{u'x': 8.0, u'_id': ObjectId('51e3ce08915082db3df32bf7')} 
{u'x': 7.0, u'_id': ObjectId('51e3ce08915082db3df32bf6')} 
{u'x': 6.0, u'_id': ObjectId('51e3ce08915082db3df32bf5')} 
{u'x': 5.0, u'_id': ObjectId('51e3ce08915082db3df32bf4')} 
31


See how easy this is (again)? The Python syntax is pretty much identical to the MongoDB syntax and their dictionaries are a perfect match. No conversion needed (DALs and ORMs, rot in Hell!).

Robert Burns, the famous 18th-century Scottish poet, once wrote: "Freedom an' whisky gang thegither!". With all due respect for such a wise man, please let me add: "So do MongoDB and Python, especially with a glass of 18-year old Glenlivet". Open Source (on the) rocks :D

That's it for today. Now write some code, will ya?

No comments:

Post a Comment