Python MongoDB Setup
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
sudo apt-get install python-setuptools or sudo yum install python-setuptools
iterations, although it seems to be usually installed with most Linux distributions these days.
If easy_install or pip is not installed on Windows, try reformatting your hard disk and installing
a real OS, or if that is too inconvenient go here. The key here is to install pymongo.
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 1
Python
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 2
Here is the complete listing to make the cut and paste crowd (like me), happy.
Listing: Complete Python listing
import 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:
|
No comments:
Post a Comment