python連接mongodb操作數(shù)據(jù)示例(mongodb數(shù)據(jù)庫配置類)
更新時間:2013年12月31日 14:45:57 作者:
這篇文章主要介紹了python連接mongodb操作數(shù)據(jù)示例,主要包括插入數(shù)據(jù)、更新數(shù)據(jù)、查詢數(shù)據(jù)、刪除數(shù)據(jù)等
一、相關(guān)代碼
數(shù)據(jù)庫配置類 MongoDBConn.py
復(fù)制代碼 代碼如下:
#encoding=utf-8
'''
Mongo Conn連接類
'''
import pymongo
class DBConn:
conn = None
servers = "mongodb://localhost:27017"
def connect(self):
self.conn = pymongo.Connection(self.servers)
def close(self):
return self.conn.disconnect()
def getConn(self):
return self.conn
MongoDemo.py 類
復(fù)制代碼 代碼如下:
#encoding=utf-8
'''
Mongo操作Demo
Done:
'''
import MongoDBConn
dbconn = MongoDBConn.DBConn()
conn = None
lifeba_users = None
def process():
#建立連接
dbconn.connect()
global conn
conn = dbconn.getConn()
#列出server_info信息
print conn.server_info()
#列出全部數(shù)據(jù)庫
databases = conn.database_names()
print databases
#刪除庫和表
dropTable()
#添加數(shù)據(jù)庫lifeba及表(collections)users
createTable()
#插入數(shù)據(jù)
insertDatas()
#更新數(shù)據(jù)
updateData()
#查詢數(shù)據(jù)
queryData()
#刪除數(shù)據(jù)
deleteData()
#釋放連接
dbconn.close()
def insertDatas():
datas=[{"name":"steven1","realname":"測試1","age":25},
{"name":"steven2","realname":"測試2","age":26},
{"name":"steven1","realname":"測試3","age":23}]
lifeba_users.insert(datas)
def updateData():
'''只修改最后一條匹配到的數(shù)據(jù)
第3個參數(shù)設(shè)置為True,沒找到該數(shù)據(jù)就添加一條
第4個參數(shù)設(shè)置為True,有多條記錄就不更新
'''
lifeba_users.update({'name':'steven1'},{'$set':{'realname':'測試1修改'}}, False,False)
def deleteData():
lifeba_users.remove({'name':'steven1'})
def queryData():
#查詢?nèi)繑?shù)據(jù)
rows = lifeba_users.find()
printResult(rows)
#查詢一個數(shù)據(jù)
print lifeba_users.find_one()
#帶條件查詢
printResult(lifeba_users.find({'name':'steven2'}))
printResult(lifeba_users.find({'name':{'$gt':25}}))
def createTable():
'''創(chuàng)建庫和表'''
global lifeba_users
lifeba_users = conn.lifeba.users
def dropTable():
'''刪除表'''
global conn
conn.drop_database("lifeba")
def printResult(rows):
for row in rows:
for key in row.keys():#遍歷字典
print row[key], #加, 不換行打印
print ''
if __name__ == '__main__':
process()
您可能感興趣的文章:
相關(guān)文章
Jupyter Notebook 如何修改字體和大小以及更改字體樣式
這篇文章主要介紹了Jupyter Notebook 如何修改字體和大小以及更改字體樣式的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06
詳解python selenium 爬取網(wǎng)易云音樂歌單名
這篇文章主要介紹了python selenium爬取網(wǎng)易云音樂歌單名,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03
Python實現(xiàn)結(jié)構(gòu)體代碼實例
這篇文章主要介紹了Python實現(xiàn)結(jié)構(gòu)體代碼實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-02-02
使用python畫出邏輯斯蒂映射(logistic map)中的分叉圖案例
這篇文章主要介紹了使用python畫出邏輯斯蒂映射(logistic map)中的分叉圖案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12

