|
Once you have it all setup, you will can create some code that is equivalent to the first console examples as shown in figure 11.
Figure 11: Python code listing part 1- 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
复制代码 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 12.
Figure 12: Python code listing part 2- print employees.find({"name":"Rick Hightower"})[0]
- # Output
- # {u'gender':u'm',u'age':42.0,u'_id':ObjectId('4f964d3000b5874e7a163895'),
- # u'name':u'Rick Hightower',u'phone':u'520-555-1212'}
- cursor = employees.find({"age":{"$lt":35}})
- for employee in cursor:
- print "under 35: %s" % employee
- # Output
- #under 35: {u'gender':u'f',u'age': 30, u'_id':ObjectId("4f985a7f72323465ed25cccd'),u'name':
- #u'Diana Hightower', u'phone':u'520-555-1212'}
- #under 35:{u'gender':u'm',u'age':8,u'_id':ObjectId('4f9e111980cbd54eea000000'),u'name':
- #u'Lucas Hightower', u'phone':u'520-555-1212'}
- diana = employees.find_one({"_id":ObjectId("4f984cce72320612f8f432bb")})
- print "Diana %s" % diana
- #Output
- #Diana {u'gender': u'f', u'age':30, u'_id':ObjectId('4f984cce72320612f8f432bb'),
- #u'name': u'Diana Hightower', u'phone': u'520-555-1212'}
复制代码 |
|