Python Mongo操作

來源:互聯網
上載者:User

標籤:

# -*- coding: utf-8 -*-‘‘‘Python Mongo操作DemoDone:‘‘‘from pymongo import MongoClientconn = Nonetopics = Noneusers=Nonedef process():  connection=MongoClient(‘localhost‘, 27017) global conn conn = connection; #列出server_info資訊 #print conn.server_info() #列出全部資料庫 databases = conn.database_names() print databases topics = conn.node.topics users=conn.node.users ret=users.find({‘loginname‘:‘dingxiaoyuehao‘}) if ret and ret.count() > 0: print "yes" else: print "no" #刪除庫和表 #dropTable() #添加資料庫lifeba及表(collections)users #createTable() #插入資料 #insertDatas() #更新資料 #updateData() #查詢資料 #queryData() #刪除資料 #deleteData() #釋放串連 #dbconn.close()def insertDatas(): datas=[{"name":"steven1","realname":"測試1","age":25}, {"name":"steven2","realname":"測試2","age":26}, {"name":"steven1","realname":"測試3","age":23}] topics.insert(datas)def updateData(): ‘‘‘只修改最後一條匹配到的資料 第3個參數設定為True,沒找到該資料就添加一條 第4個參數設定為True,有多條記錄就不更新 ‘‘‘ topics.update({‘name‘:‘steven1‘},{‘$set‘:{‘realname‘:‘測試1修改‘}}, False,False)def deleteData(): topics.remove({‘name‘:‘steven1‘})def queryData(): #查詢全部資料 rows = topics.find() printResult(rows) #查詢一個資料 print topics.find_one() #帶條件查詢 printResult(topics.find({‘name‘:‘steven2‘})) printResult(topics.find({‘name‘:{‘$gt‘:25}}))def createTable(): ‘‘‘建立庫和表‘‘‘ global topics topics = conn.lifeba.topicsdef dropTable(): ‘‘‘刪除表‘‘‘ global conn conn.drop_database("lifeba")def printResult(rows): for row in rows: for key in row.keys():#遍曆字典 print row[key].encode(‘gb2312‘), #加, 不換行列印 print ‘‘if __name__ == ‘__main__‘: process()

  

Python Mongo操作

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.