search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

Python3中PyMongo的用法

感謝關注天善智能,走好數據之路↑↑↑

歡迎關注天善智能,我們是專註於商業智能BI,大數據,數據分析領域的垂直社區,學習,問答、求職一站式搞定!

MongoDB存儲

在這裡我們來看一下Python3下MongoDB的存儲操作,在本節開始之前請確保你已經安裝好了MongoDB並啟動了其服務,另外安裝好了Python的PyMongo庫。

連接MongoDB

連接MongoDB我們需要使用PyMongo庫裡面的MongoClient,一般來說傳入MongoDB的IP及埠即可,第一個參數為地址host,第二個參數為埠port,埠如果不傳默認是27017。

import pymongoclient = pymongo.MongoClient(host='localhost' port=27017)

這樣我們就可以創建一個MongoDB的連接對象了。

另外MongoClient的第一個參數host還可以直接傳MongoDB的連接字元串,以mongodb開頭,例如:

client = MongoClient('mongodb://localhost:27017/')

可以達到同樣的連接效果。

指定資料庫

MongoDB中還分為一個個資料庫,我們接下來的一步就是指定要操作哪個資料庫,在這裡我以test資料庫為例進行說明,所以下一步我們需要在程序中指定要使用的資料庫。

db = client.test

調用client的test屬性即可返回test資料庫,當然也可以這樣來指定:

db = client['test']

兩種方式是等價的。

指定集合

MongoDB的每個資料庫又包含了許多集合Collection,也就類似與關係型資料庫中的表,下一步我們需要指定要操作的集合,在這裡我們指定一個集合名稱為students,學生集合。還是和指定資料庫類似,指定集合也有兩種方式。

collection = db.studentscollection = db['students']

插入數據

接下來我們便可以進行數據插入了,對於students這個Collection,我們新建一條學生數據,以字典的形式表示:

student = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}

在這裡我們指定了學生的學號、姓名、年齡和性別,然後接下來直接調用collection的insert方法即可插入數據。

result = collection.insert(student)print(result)

在MongoDB中,每條數據其實都有一個_id屬性來唯一標識,如果沒有顯式指明_id,MongoDB會自動產生一個ObjectId類型的_id屬性。insert方法會在執行后返回的_id值。

運行結果:

5932a68615c2606814c91f3d

當然我們也可以同時插入多條數據,只需要以列表形式傳遞即可,示例如下:

student1 = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}student2 = { 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}result = collection.insert([student1, student2])print(result)

返回的結果是對應的_id的集合,運行結果:

[ObjectId('5932a80115c2606a59e8a048'), ObjectId('5932a80115c2606a59e8a049')]

實際上在PyMongo 3.X版本中,insert方法官方已經不推薦使用了,當然繼續使用也沒有什麼問題,官方推薦使用insert_one和insert_many方法將插入單條和多條記錄分開。

student = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}result = collection.insert_one(student)print(result)print(result.inserted_id)

運行結果:

<pymongo.results.InsertOneResult object at 0x10d68b5585932ab0f15c2606f0c1cf6c5

返回結果和insert方法不同,這次返回的是InsertOneResult對象,我們可以調用其inserted_id屬性獲取_id。

對於insert_many方法,我們可以將數據以列表形式傳遞即可,示例如下:

student1 = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}student2 = { 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}result = collection.insert_many([student1, student2])print(result)print(result.inserted_ids)

insert_many方法返回的類型是InsertManyResult,調用inserted_ids屬性可以獲取插入數據的_id列表,運行結果:

<pymongo.results.InsertManyResult object at 0x101dea558[ObjectId('5932abf415c2607083d3b2ac'), ObjectId('5932abf415c2607083d3b2ad')]

查詢

插入數據后我們可以利用find_one或find方法進行查詢,find_one查詢得到是單個結果,find則返回多個結果。

result = collection.find_one({'name': 'Mike'})print(type(result))print(result)

在這裡我們查詢name為Mike的數據,它的返回結果是字典類型,運行結果:

<class 'dict'>{'_id': ObjectId('5932a80115c2606a59e8a049'), 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}

可以發現它多了一個_id屬性,這就是MongoDB在插入的過程中自動添加的。

我們也可以直接根據ObjectId來查詢,這裡需要使用bson庫裡面的ObjectId。

from bson.objectid import ObjectIdresult = collection.find_one({'_id': ObjectId('593278c115c2602667ec6bae')})print(result)

其查詢結果依然是字典類型,運行結果:

{'_id': ObjectId('593278c115c2602667ec6bae'), 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}

當然如果查詢結果不存在則會返回None。

對於多條數據的查詢,我們可以使用find方法,例如在這裡查找年齡為20的數據,示例如下:

results = collection.find({'age': 20})print(results)for result in results: print(result)

運行結果:

<pymongo.cursor.Cursor object at 0x1032d5128{'_id': ObjectId('593278c115c2602667ec6bae'), 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}{'_id': ObjectId('593278c815c2602678bb2b8d'), 'id': '20170102', 'name': 'Kevin', 'age': 20, 'gender': 'male'}{'_id': ObjectId('593278d815c260269d7645a8'), 'id': '20170103', 'name': 'Harden', 'age': 20, 'gender': 'male'}

返回結果是Cursor類型,相當於一個生成器,我們需要遍歷取到所有的結果,每一個結果都是字典類型。

如果要查詢年齡大於20的數據,則寫法如下:

results = collection.find({'age': {'$gt': 20}})

在這裡查詢的條件鍵值已經不是單純的數字了,而是一個字典,其鍵名為比較符號$gt,意思是大於,鍵值為20,這樣便可以查詢出所有年齡大於20的數據。

在這裡將比較符號歸納如下表:

符號含義示例$lt小於{'age': {'$lt': 20}}$gt大於{'age': {'$gt': 20}}$lte小於等於{'age': {'$lte': 20}}$gte大於等於{'age': {'$gte': 20}}$ne不等於{'age': {'$ne': 20}}$in在範圍內{'age': {'$in': [20, 23]}}$nin不在範圍內{'age': {'$nin': [20, 23]}}

另外還可以進行正則匹配查詢,例如查詢名字以M開頭的學生數據,示例如下:

results = collection.find({'name': {'$regex': '^M.*'}})

在這裡使用了$regex來指定正則匹配,^M.*代表以M開頭的正則表達式,這樣就可以查詢所有符合該正則的結果。

在這裡將一些功能符號再歸類如下:

符號含義示例示例含義$regex匹配正則{'name': {'$regex': '^M.*'}}name以M開頭$exists屬性是否存在{'name': {'$exists': True}}name屬性存在$type類型判斷{'age': {'$type': 'int'}}age的類型為int$mod數字模操作{'age': {'$mod': [5, 0]}}年齡模5餘0$text文本查詢{'$text': {'$search': 'Mike'}}text類型的屬性中包含Mike字元串$where高級條件查詢{'$where': 'obj.fans_count == obj.follows_count'}自身冬粉數等於關注數

這些操作的更詳細用法在可以在MongoDB官方文檔找到:https://docs.mongodb.com/manual/reference/operator/query/

計數

要統計查詢結果有多少條數據,可以調用count方法,如統計所有數據條數:

count = collection.find.countprint(count)

或者統計符合某個條件的數據:

count = collection.find({'age': 20}).countprint(count)

排序

可以調用sort方法,傳入排序的欄位及升降序標誌即可,示例如下:

results = collection.find.sort('name', pymongo.ASCENDING)print([result['name'] for result in results])

運行結果:

['Harden', 'Jordan', 'Kevin', 'Mark', 'Mike']

偏移

在某些情況下我們可能想只取某幾個元素,在這裡可以利用skip方法偏移幾個位置,比如偏移2,就忽略前2個元素,得到第三個及以後的元素。

results = collection.find.sort('name', pymongo.ASCENDING).skip(2)print([result['name'] for result in results])

運行結果:

['Kevin', 'Mark', 'Mike']

另外還可以用limit方法指定要取的結果個數,示例如下:

results = collection.find.sort('name', pymongo.ASCENDING).skip(2).limit(2)print([result['name'] for result in results])

運行結果:

['Kevin', 'Mark']

如果不加limit原本會返回三個結果,加了限制之後,會截取2個結果返回。

值得注意的是,在資料庫數量非常龐大的時候,如千萬、億級別,最好不要使用大的偏移量來查詢數據,很可能會導致內存溢出,可以使用類似find({'_id': {'$gt': ObjectId('593278c815c2602678bb2b8d')}}) 這樣的方法來查詢,記錄好上次查詢的_id。

更新

對於數據更新可以使用update方法,指定更新的條件和更新后的數據即可,例如:

condition = {'name': 'Kevin'}student = collection.find_one(condition)student['age'] = 25result = collection.update(condition, student)print(result)

在這裡我們將name為Kevin的數據的年齡進行更新,首先指定查詢條件,然後將數據查詢出來,修改年齡,之後調用update方法將原條件和修改後的數據傳入,即可完成數據的更新。

運行結果:

{'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}

返回結果是字典形式,ok即代表執行成功,nModified代表影響的數據條數。

另外update方法其實也是官方不推薦使用的方法,在這裡也分了update_one方法和update_many方法,用法更加嚴格,第二個參數需要使用$類型操作符作為字典的鍵名,我們用示例感受一下。

condition = {'name': 'Kevin'}student = collection.find_one(condition)student['age'] = 26result = collection.update_one(condition, {'$set': student})print(result)print(result.matched_count, result.modified_count)

在這裡調用了update_one方法,第二個參數不能再直接傳入修改後的字典,而是需要使用{'$set': student}這樣的形式,其返回結果是UpdateResult類型,然後調用matched_count和modified_count屬性分別可以獲得匹配的數據條數和影響的數據條數。

運行結果:

<pymongo.results.UpdateResult object at 0x10d17b6781 0

我們再看一個例子:

condition = {'age': {'$gt': 20}}result = collection.update_one(condition, {'$inc': {'age': 1}})print(result)print(result.matched_count, result.modified_count)

在這裡我們指定查詢條件為年齡大於20,然後更新條件為{'$inc': {'age': 1}},也就是年齡加1,執行之後會講第一條符合條件的數據年齡加1。

運行結果:

<pymongo.results.UpdateResult object at 0x10b8874c81 1

可以看到匹配條數為1條,影響條數也為1條。

如果調用update_many方法,則會將所有符合條件的數據都更新,示例如下:

condition = {'age': {'$gt': 20}}result = collection.update_many(condition, {'$inc': {'age': 1}})print(result)print(result.matched_count, result.modified_count)

這時候匹配條數就不再為1條了,運行結果如下:

<pymongo.results.UpdateResult object at 0x10c6384c83 3

可以看到這時所有匹配到的數據都會被更新。

刪除

刪除操作比較簡單,直接調用remove方法指定刪除的條件即可,符合條件的所有數據均會被刪除,示例如下:

result = collection.remove({'name': 'Kevin'})print(result)

運行結果:

{'ok': 1, 'n': 1}

另外依然存在兩個新的推薦方法,delete_one和delete_many方法,示例如下:

result = collection.delete_one({'name': 'Kevin'})print(result)print(result.deleted_count)result = collection.delete_many({'age': {'$lt': 25}})print(result.deleted_count)

運行結果:

<pymongo.results.DeleteResult object at 0x10e6ba4c814

delete_one即刪除第一條符合條件的數據,delete_many即刪除所有符合條件的數據,返回結果是DeleteResult類型,可以調用deleted_count屬性獲取刪除的數據條數。

另外PyMongo還提供了一些組合方法,如find_one_and_delete、find_one_and_replace、find_one_and_update,就是查找后刪除、替換、更新操作,用法與上述方法基本一致。

另外還可以對索引進行操作,如create_index、create_indexes、drop_index等。

詳細用法可以參見官方文檔:http://api.mongodb.com/python/current/api/pymongo/collection.html

另外還有對資料庫、集合本身以及其他的一些操作,在這不再一一講解,可以參見官方文檔:http://api.mongodb.com/python/current/api/pymongo/

本文作者:天善智能社區 崔慶才

崔慶才老師的推薦課程:自己動手,豐衣足食!Python3網路爬蟲實戰案例

課程詳情請見:https://edu.hellobi.com/course/157

課程特色:

循序漸進。環境篇、基礎篇、進階篇、框架篇、分散式篇,由淺入深,娓娓道來,進階無憂;

案例為王。貓眼電影、今日頭條街拍、淘寶商品美食、微信文章、知乎用戶信息等案例,結合反爬策略,例例實戰,夠生活、有質量、有趣味,寓課於樂;

詮釋全面。理論介紹之上的代碼級剖析,學員與講師之間、學員之間,高效高頻答疑與溝通,亦師亦友,互動共進;

思路制勝。通過課程,培養爬蟲開發過程中洞察問題、分析問題,提出解決方案能力,一課所獲,長久收益;



熱門推薦

本文由 yidianzixun 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦