python使用pymongo操作mongo的完整步驟

 

原文鏈接:https://www.jb51.net/article/159652.htm

這篇文章主要給大家介紹了關於python使用pymongo操作mongo的完整步驟,文中通過示例代碼介紹的非常詳細,對大家學習或者使用python具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧

 

目錄

 

前言

MongoDB是由C++語言編寫的非關係型數據庫,是一個基於分佈式文件存儲的開源數據庫系統,其內容存儲形式類似JSON對象,它的字段值可以包含其他文檔、數組及文檔數組,非常靈活。在這一節中,我們就來看看Python 3下MongoDB的存儲操作。

 

1. 準備工作

在開始之前,請確保已經安裝好了MongoDB並啓動了其服務,並且安裝好了Python的PyMongo庫。

 

2. 連接MongoDB

連接MongoDB時,我們需要使用PyMongo庫裏面的MongoClient。一般來說,傳入MongoDB的IP及端口即可,其中第一個參數爲地址host,第二個參數爲端口port(如果不給它傳遞參數,默認是27017):

?

1

2

import pymongo

client = pymongo.MongoClient(host='localhost', port=27017)

這樣就可以創建MongoDB的連接對象了。

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

?

1

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

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

 

3. 指定數據庫

MongoDB中可以建立多個數據庫,接下來我們需要指定操作哪個數據庫。這裏我們以test數據庫爲例來說明,下一步需要在程序中指定要使用的數據庫:

?

1

db = client.test

這裏調用client的test屬性即可返回test數據庫。當然,我們也可以這樣指定:

?

1

db = client['test']

這兩種方式是等價的。

 

4. 指定集合

MongoDB的每個數據庫又包含許多集合(collection),它們類似於關係型數據庫中的表。

下一步需要指定要操作的集合,這裏指定一個集合名稱爲students。與指定數據庫類似,指定集合也有兩種方式:

?

1

collection = db.students

?

1

collection = db['students']

這樣我們便聲明瞭一個Collection對象。

 

5. 插入數據

接下來,便可以插入數據了。對於students這個集合,新建一條學生數據,這條數據以字典形式表示:

?

1

2

3

4

5

6

student = {

 'id': '20170101',

 'name': 'Jordan',

 'age': 20,

 'gender': 'male'

}

這裏指定了學生的學號、姓名、年齡和性別。接下來,直接調用collection的insert()方法即可插入數據,代碼如下:

?

1

2

result = collection.insert(student)

print(result)

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

運行結果如下:

5932a68615c2606814c91f3d

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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()方法來分別插入單條記錄和多條記錄,示例如下:

?

1

2

3

4

5

6

7

8

9

10

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()方法,我們可以將數據以列表形式傳遞,示例如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

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列表。

 

6. 查詢

插入數據後,我們可以利用find_one()或find()方法進行查詢,其中find_one()查詢得到的是單個結果,find()則返回一個生成器對象。示例如下:

?

1

2

3

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:

?

1

2

3

4

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的數據,示例如下:

?

1

2

3

4

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的數據,則寫法如下:

?

1

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開頭的學生數據,示例如下:

?

1

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/。

 

7. 計數

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

?

1

2

count = collection.find().count()

print(count)

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

?

1

2

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

print(count)

運行結果是一個數值,即符合條件的數據條數。

 

8. 排序

排序時,直接調用sort()方法,並在其中傳入排序的字段及升降序標誌即可。示例如下:

?

1

2

results = collection.find().sort('name', pymongo.ASCENDING)

print([result['name'] for result in results])

運行結果如下:

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

這裏我們調用pymongo.ASCENDING指定升序。如果要降序排列,可以傳入pymongo.DESCENDING。

 

9. 偏移

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

?

1

2

results = collection.find().sort('name', pymongo.ASCENDING).skip(2)

print([result['name'] for result in results])

運行結果如下:

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

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

?

1

2

results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2)

print([result['name'] for result in results])

運行結果如下:

['Kevin', 'Mark']

如果不使用limit()方法,原本會返回三個結果,加了限制後,會截取兩個結果返回。

值得注意的是,在數據庫數量非常龐大的時候,如千萬、億級別,最好不要使用大的偏移量來查詢數據,因爲這樣很可能導致內存溢出。此時可以使用類似如下操作來查詢:

?

1

2

from bson.objectid import ObjectId

collection.find({'_id': {'$gt': ObjectId('593278c815c2602678bb2b8d')}})

這時需要記錄好上次查詢的_id。

 

10. 更新

對於數據更新,我們可以使用update()方法,指定更新的條件和更新後的數據即可。例如:

?

1

2

3

4

5

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操作符對數據進行更新,代碼如下:

?

1

result = collection.update(condition, {'$set': student})

這樣可以只更新student字典內存在的字段。如果原先還有其他字段,則不會更新,也不會刪除。而如果不用$set的話,則會把之前的數據全部用student字典替換;如果原本存在其他字段,則會被刪除。

另外,update()方法其實也是官方不推薦使用的方法。這裏也分爲update_one()方法和update_many()方法,用法更加嚴格,它們的第二個參數需要使用$類型操作符作爲字典的鍵名,示例如下:

?

1

2

3

4

5

6

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

我們再看一個例子:

?

1

2

3

4

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()方法,則會將所有符合條件的數據都更新,示例如下:

?

1

2

3

4

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

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

 

11. 刪除

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

?

1

2

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

print(result)

運行結果如下:

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

另外,這裏依然存在兩個新的推薦方法——delete_one()和delete_many()。示例如下:

?

1

2

3

4

5

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屬性獲取刪除的數據條數。

 

12. 其他操作

另外,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/。

 

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章