首先需要安裝pymongo模組,模組下載地址
https://pypi.python.org/pypi/pymongo/#downloads
選擇適合的版本,進行安裝,安裝完成後就可以連結你的mongodb了
pymongodb-2.3.tar.gz下載: http://download.csdn.net/detail/wanzhuan2010/6889887
#encoding:utf=8import pymongoconnection=pymongo.Connection('10.32.38.50',27017)#選擇myblog庫db=connection.myblog# 使用users集合collection=db.users# 添加單條資料到集合中user = {"name":"cui","age":"10"}collection.insert(user)#同時添加多條資料到集合中users=[{"name":"cui","age":"9"},{"name":"cui","age":"11"}]collection.insert(users)#查詢單條記錄print collection.find_one()#查詢所有記錄for data in collection.find():print data#查詢此集合中資料條數print collection.count()#簡單參數查詢for data in collection.find({"name":"1"}):print data#使用find_one擷取一條記錄print collection.find_one({"name":"1"})#進階查詢print "__________________________________________"print '''collection.find({"age":{"$gt":"10"}})'''print "__________________________________________"for data in collection.find({"age":{"$gt":"10"}}).sort("age"):print data# 查看db下的所有集合print db.collection_names()
參考: http://www.oschina.net/question/54100_27233