本篇文章主要介紹了python之PyMongo使用總結,詳細的介紹了PyMongo模組的使用,具有一定的參考價值,有興趣的可以了解一下
# PyMongo是什麼
PyMongo是驅動程序,讓python程式能夠使用Mongodb資料庫,使用python編寫而成.
#fall:Ubuntu 14.04+python2.7+MongoDB 2.4
先去官網下載軟體包,位址點選開啟連結.解壓縮後進入,使用python setup.py install 進行安裝
#或用pip安裝pip -m install pymongo
建立連接
import pymongo client = pymongo.MongoClient('localhost', 27017)
或可以這樣
import pymongo client = MongoClient('mongodb://localhost:27017/')
db = client.mydb #或者 db = client['mydb']
連接聚集
#聚集相當於關係型資料庫中的表格
collection = db.my_collection #或者 collection = db['my_collection']
查看資料庫下所有聚集名稱
db.collection_names()
collection.insert({"key1":"value1","key2","value2"})
全部刪除
collection.remove()
按條件刪除
collection.remove({"key1":"value1"})
更新記錄
複製程式碼 程式碼如下:
collection.update({"key1": "value1"}, {"$set": {"key2": "value2", "key3": "value3"}})
查詢一筆記錄:find_one()不帶任何參數傳回第一筆記錄.帶參數則按條件查找返回
collection.find_one() collection.find_one({"key1":"value1"})
查詢多個記錄:find()不帶參數傳回所有記錄,帶參數按條件查找返回
collection.find() collection.find({"key1":"value1"})
查看聚集的多筆記錄
for item in collection.find(): print item
查看聚集記錄的總數
print collection.find().count()
#查詢結果排序
單列上排序
collection.find().sort("key1") # 默认为升序 collection.find().sort("key1", pymongo.ASCENDING) # 升序 collection.find().sort("key1", pymongo.DESCENDING) # 降序
多列上排序
複製程式碼 程式碼如下:
collection.find().sort([("key1", pymongo.ASCENDING), ("key2", pymongo.DESCENDING)])
實例1:
#!/usr/bin/env python #coding:utf-8 # Author: --<qingfengkuyu> # Purpose: MongoDB的使用 # Created: 2014/4/14 #32位的版本最多只能存储2.5GB的数据(NoSQLFan:最大文件尺寸为2G,生产环境推荐64位) import pymongo import datetime import random #创建连接 conn = pymongo.Connection('10.11.1.70',27017) #连接数据库 db = conn.study #db = conn['study'] #打印所有聚集名称,连接聚集 print u'所有聚集:',db.collection_names() posts = db.post #posts = db['post'] print posts #插入记录 new_post = {"AccountID":22,"UserName":"libing",'date':datetime.datetime.now()} new_posts = [{"AccountID":22,"UserName":"liuw",'date':datetime.datetime.now()}, {"AccountID":23,"UserName":"urling",'date':datetime.datetime.now()}]#每条记录插入时间都不一样 posts.insert(new_post) #posts.insert(new_posts)#批量插入多条数据 #删除记录 print u'删除指定记录:\n',posts.find_one({"AccountID":22,"UserName":"libing"}) posts.remove({"AccountID":22,"UserName":"libing"}) #修改聚集内的记录 posts.update({"UserName":"urling"},{"$set":{'AccountID':random.randint(20,50)}}) #查询记录,统计记录数量 print u'记录总计为:',posts.count(),posts.find().count() print u'查询单条记录:\n',posts.find_one() print posts.find_one({"UserName":"liuw"}) #查询所有记录 print u'查询多条记录:' #for item in posts.find():#查询全部记录 #for item in posts.find({"UserName":"urling"}):#查询指定记录 #for item in posts.find().sort("UserName"):#查询结果根据UserName排序,默认为升序 #for item in posts.find().sort("UserName",pymongo.ASCENDING):#查询结果根据UserName排序,ASCENDING为升序,DESCENDING为降序 for item in posts.find().sort([("UserName",pymongo.ASCENDING),('date',pymongo.DESCENDING)]):#查询结果根据多列排序 print item #查看查询语句的性能 #posts.create_index([("UserName", pymongo.ASCENDING), ("date", pymongo.DESCENDING)])#加索引 print posts.find().sort([("UserName",pymongo.ASCENDING),('date',pymongo.DESCENDING)]).explain()["cursor"]#未加索引用BasicCursor查询记录 print posts.find().sort([("UserName",pymongo.ASCENDING),('date',pymongo.DESCENDING)]).explain()["nscanned"]#查询语句执行时查询的记录数
以上是詳解python之PyMongo的使用總結的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Python是解釋型語言,但也包含編譯過程。 1)Python代碼先編譯成字節碼。 2)字節碼由Python虛擬機解釋執行。 3)這種混合機制使Python既靈活又高效,但執行速度不如完全編譯型語言。

UseeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.forloopsareIdealForkNownsences,而WhileLeleLeleLeleLeleLoopSituationSituationsItuationsItuationSuationSituationswithUndEtermentersitations。

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐個偏置,零indexingissues,andnestedloopineflinefficiencies

forloopsareadvantageousforknowniterations and sequests,供應模擬性和可讀性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

WebStorm Mac版
好用的JavaScript開發工具

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

記事本++7.3.1
好用且免費的程式碼編輯器