Python MongoDB SetupSee setup guide to see how to install MongoDB. Setting up Python and MongoDB are quite easy since Python has its own package manager. To install mongodb lib for Python MAC OSX, you would do the following: $ sudo env ARCHFLAGS='-arch i386 -arch x86_64' $ python -m easy_install pymongo To install Python MongoDB on Linux or Windows do the following: $ easy_install pymongo or $ pip install pymongo If you don't have easy_install on your Linux box you may have to do some Once you have it all setup, you will can create some code that is equivalent to the first console examples as shown in figure 1. Figure 1: Python code listing part 1Python does have literals for maps so working with Python is much closer to the JavaScript/Console from earlier than Java is. Like Java there are libraries for Python that work with MongoDB (MongoEngine, MongoKit, and more). Even executing queries is very close to the JavaScript experience as shown in figure 2. Figure 2: Python code listing part 2Here is the complete listing to make the cut and paste crowd (like me), happy. Listing: Complete Python listingimport pymongo from bson.objectid import ObjectId connection = pymongo.Connection() db = connection["tutorial"] employees = db["employees"] employees.insert({"name": "Lucas Hightower", 'gender':'m', 'phone':'520-555-1212', 'age':8}) cursor = db.employees.find() for employee in db.employees.find(): print employee print employees.find({"name":"Rick Hightower"})[0] cursor = employees.find({"age": {"$lt": 35}}) for employee in cursor: print "under 35: %s" % employee diana = employees.find_one({"_id":ObjectId("4f984cce72320612f8f432bb")}) print "Diana %s" % diana If you would like to learn more about MongoDB consider the following resources:
The output for the Python example is as follows: {u'gender': u'm', u'age': 42.0, u'_id': ObjectId('4f964d3000b5874e7a163895'), u'name': u'Rick Hightower', u'phone': u'520-555-1212'} {u'gender': u'f', u'age': 30, u'_id': ObjectId('4f984cae72329d0ecd8716c8'), u'name': u'Diana Hightower', u'phone': u'520-555-1212'} {u'gender': u'm', u'age': 8, u'_id': ObjectId('4f9e111980cbd54eea000000'), u'name': u'Lucas Hightower', u'phone': u'520-555-1212'} |
Mammatus Blog >