1. 程式人生 > >使用python語言操作MongoDB

使用python語言操作MongoDB

MongoDB是一個跨平臺的NoSQL,基於Key-Value形式儲存資料。其儲存格式非常類似於Python的字典,因此用Python操作MongoDB會非常的容易。

pymongo的兩種安裝命令

pip install pymongo

easy_install pymongo

Python操作MongoDB

#encoding:utf=8  
import pymongo  

connection=pymongo.Connection('10.32.38.50',27017)  

#選擇myblog庫  
db=connection.myblog  

# 使用users集合  
collection=db.users #新增命令如下: # 新增單條資料到集合中 user = {"name":"xiaoxu","age":"23"} collection.insert(user) #新增資料 collection.save(users) #新增資料 #同時新增多條資料到集合中 users=[{"name":"xiaoxu","age":"23"},{"name":"xiaoli","age":"20"}] collection.insert(users) #新增資料 collection.save(users) #新增資料 #刪除命令如下:
collection.remove({"name":"xiaoxu"}) #修改命令如下: collection.update(xxxx) #查詢命令如下: #查詢單條記錄 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"})

例項如下:

#-*-coding:utf8-*-
import pymongo

connection = pymongo.MongoClient()
tdb = connection.Jikexueyuan
post_info = tdb.test

jike = {'name':u'極客', 'age':'5', 'skill': 'Python'}
god = {'name': u'玉皇大帝', 'age': 36000, 'skill': 'creatanything', 'other': u'王母娘娘不是他的老婆'}
godslaver = {'name': u'月老', 'age': 'unknown', 'other': u'他的老婆叫孟婆'}
post_info.insert(jike)
post_info.insert(god)
post_info.insert(godslaver)
post_info.remove({'name': u'極客'})

print u'操作資料庫完成!'