MongoDB是由C++語言編寫的非關係型數據庫,是一個基於分佈式文件存儲的開源數據庫系統,其內容存儲形式相似JSON對象,它的字段值能夠包含其餘文檔、數組及文檔數組,很是靈活。在這一節中,咱們就來看看Python 3下MongoDB的存儲操做。
html
在開始以前,請確保已經安裝好了MongoDB並啓動了其服務,而且安裝好了Python的PyMongo庫。
python
鏈接MongoDB時,咱們須要使用PyMongo庫裏面的MongoClient
。通常來講,傳入MongoDB的IP及端口便可,其中第一個參數爲地址host
,第二個參數爲端口port
(若是不給它傳遞參數,默認是27017):
正則表達式
import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)複製代碼
這樣就能夠建立MongoDB的鏈接對象了。mongodb
另外,MongoClient
的第一個參數host
還能夠直接傳入MongoDB的鏈接字符串,它以mongodb
開頭,例如:數據庫
client = MongoClient('mongodb://localhost:27017/')複製代碼
這也能夠達到一樣的鏈接效果。api
MongoDB中能夠創建多個數據庫,接下來咱們須要指定操做哪一個數據庫。這裏咱們以test數據庫爲例來講明,下一步須要在程序中指定要使用的數據庫:
數組
db = client.test複製代碼
這裏調用client
的test
屬性便可返回test數據庫。固然,咱們也能夠這樣指定:bash
db = client['test']複製代碼
這兩種方式是等價的。微信
MongoDB的每一個數據庫又包含許多集合(collection),它們相似於關係型數據庫中的表。
網絡
下一步須要指定要操做的集合,這裏指定一個集合名稱爲students。與指定數據庫相似,指定集合也有兩種方式:
collection = db.students複製代碼
collection = db['students']複製代碼
這樣咱們便聲明瞭一個Collection
對象。
接下來,即可以插入數據了。對於students這個集合,新建一條學生數據,這條數據以字典形式表示:
student = {
'id': '20170101',
'name': 'Jordan',
'age': 20,
'gender': 'male'
}複製代碼
這裏指定了學生的學號、姓名、年齡和性別。接下來,直接調用collection
的insert()
方法便可插入數據,代碼以下:
result = collection.insert(student)
print(result)複製代碼
在MongoDB中,每條數據其實都有一個_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 0x10d68b558>
5932ab0f15c2606f0c1cf6c5複製代碼
與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)複製代碼
運行結果以下:
<pymongo.results.InsertManyResult object at 0x101dea558>
[ObjectId('5932abf415c2607083d3b2ac'), ObjectId('5932abf415c2607083d3b2ad')]複製代碼
該方法返回的類型是InsertManyResult
,調用inserted_ids
屬性能夠獲取插入數據的_id
列表。
插入數據後,咱們能夠利用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 ObjectId
result = 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。
這裏將比較符號概括爲下表。
符號 | 含義 | 示例 |
---|---|---|
$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().count()
print(count)複製代碼
或者統計符合某個條件的數據:
count = collection.find({'age': 20}).count()
print(count)複製代碼
運行結果是一個數值,即符合條件的數據條數。
排序時,直接調用sort()
方法,並在其中傳入排序的字段及升降序標誌便可。示例以下:
results = collection.find().sort('name', pymongo.ASCENDING)
print([result['name'] for result in results])複製代碼
運行結果以下:
['Harden', 'Jordan', 'Kevin', 'Mark', 'Mike']複製代碼
這裏咱們調用pymongo.ASCENDING
指定升序。若是要降序排列,能夠傳入pymongo.DESCENDING
。
在某些狀況下,咱們可能想只取某幾個元素,這時能夠利用skip()
方法偏移幾個位置,好比偏移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()
方法,本來會返回三個結果,加了限制後,會截取兩個結果返回。
值得注意的是,在數據庫數量很是龐大的時候,如千萬、億級別,最好不要使用大的偏移量來查詢數據,由於這樣極可能致使內存溢出。此時可使用相似以下操做來查詢:
from bson.objectid import ObjectId
collection.find({'_id': {'$gt': ObjectId('593278c815c2602678bb2b8d')}})複製代碼
這時須要記錄好上次查詢的_id
。
對於數據更新,咱們可使用update()
方法,指定更新的條件和更新後的數據便可。例如:
condition = {'name': 'Kevin'}
student = collection.find_one(condition)
student['age'] = 25
result = collection.update(condition, student)
print(result)複製代碼
這裏咱們要更新name
爲Kevin
的數據的年齡:首先指定查詢條件,而後將數據查詢出來,修改年齡後調用update()
方法將原條件和修改後的數據傳入。
運行結果以下:
{'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}複製代碼
返回結果是字典形式,ok
表明執行成功,nModified
表明影響的數據條數。
另外,咱們也可使用$set
操做符對數據進行更新,代碼以下:
result = collection.update(condition, {'$set': student})複製代碼
這樣能夠只更新student
字典內存在的字段。若是原先還有其餘字段,則不會更新,也不會刪除。而若是不用$set
的話,則會把以前的數據所有用student
字典替換;若是本來存在其餘字段,則會被刪除。
另外,update()
方法其實也是官方不推薦使用的方法。這裏也分爲update_one()
方法和update_many()
方法,用法更加嚴格,它們的第二個參數須要使用$
類型操做符做爲字典的鍵名,示例以下:
condition = {'name': 'Kevin'}
student = collection.find_one(condition)
student['age'] = 26
result = 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 0x10d17b678>
1 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 0x10b8874c8>
1 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 0x10c6384c8>
3 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 0x10e6ba4c8>
1
4複製代碼
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()
等。
關於PyMongo的詳細用法,能夠參見官方文檔:http://api.mongodb.com/python/current/api/pymongo/collection.html。
另外,還有對數據庫和集合自己等的一些操做,這裏再也不一一講解,能夠參見官方文檔:http://api.mongodb.com/python/current/api/pymongo/。
本節講解了使用PyMongo操做MongoDB進行數據增刪改查的方法。
本資源首發於崔慶才的我的博客靜覓: Python3網絡爬蟲開發實戰教程 | 靜覓
如想了解更多爬蟲資訊,請關注個人我的微信公衆號:進擊的Coder
weixin.qq.com/r/5zsjOyvEZ… (二維碼自動識別)