Python 操作 MongoDB 講解詳細(xì)
1、連接MongoDB
需要使用Python
第三方庫(kù)pymongo
來(lái)連接以及操作MongoDB
,可以使用pip install pymongo
進(jìn)行安裝。 可以使用下面代碼來(lái)創(chuàng)建一個(gè)MongoDB
的連接對(duì)象。
import pymongo client = pymongo.MongoClient(host='localhost', port=27017)
一般來(lái)說(shuō)傳入兩個(gè)參數(shù)就可以,第一個(gè)參數(shù)為地址host(默認(rèn)是localhost
)第二個(gè)參數(shù)為端口port(默認(rèn)是27017)。
還有一種方法是host參數(shù)直接傳入MongoDB
的連接字符串,例如:
client = pymongo.MongoClient('mongodb://localhost:27017')
2、指定(切換)數(shù)據(jù)庫(kù)
db = client.test # 或者 # db = client['test']
如果該數(shù)據(jù)庫(kù)不存在,則自動(dòng)創(chuàng)建,否則切換到指定數(shù)據(jù)庫(kù)。 注意: 新創(chuàng)建的數(shù)據(jù)庫(kù),在沒(méi)有插入數(shù)據(jù)之前在可視化工具里看不到。
3、指定(切換)集合
MongoDB
的數(shù)據(jù)庫(kù)中包含很多集合collection
,類(lèi)似于關(guān)系型數(shù)據(jù)庫(kù)中的表,同樣,我們可以使用下面和指定數(shù)據(jù)庫(kù)類(lèi)似的方式,指定要操作的集合。
collection = db.users # 或者 collection = db['users']
4、插入數(shù)據(jù)
調(diào)用collection的insert_one()
方法可以插入單條數(shù)據(jù)。
user = { 'name': 'tigeriaf', 'gender': 'male', 'age': 24 } collection.insert_one(user)
在MongoDB
中,每條數(shù)據(jù)都有一個(gè)唯一的_id屬性,如果沒(méi)有顯式的指明_id
,MongoDB
會(huì)自動(dòng)生成ObjectId
類(lèi)型的_id屬性。
當(dāng)然我們也可以插入多條數(shù)據(jù),使用的是insert_many()
方法,數(shù)據(jù)以列表形式傳遞。
user_list = [ { 'name': 'zhangsan', 'gender': 'male', 'age': 25 }, { 'name': 'lisi', 'gender': 'male', 'age': 24 }, { 'name': 'wangwu', 'gender': 'female', 'age': 24 } ] collection.insert_many(user_list)
5、查詢(xún)數(shù)據(jù)
通過(guò)find_one()
或find()
方法進(jìn)行數(shù)據(jù)的查詢(xún),find_one()
查詢(xún)返回單個(gè)結(jié)果,find()
返回多個(gè)結(jié)果。
result = collection.find_one({'name': 'tigeriaf'}) print(type(result), result)
我們查詢(xún)的是name
為tigeriaf
的數(shù)據(jù),返回結(jié)果是字典類(lèi)型,運(yùn)行結(jié)果如下:
<class 'dict'> {'_id': ObjectId('614be85f1cc0a98d6f034de7'), 'name': 'tigeriaf', 'gender': 'male'}
對(duì)于多條數(shù)據(jù)的查詢(xún),我們可以使用find()方法,例如在這里查找年齡為20的數(shù)據(jù),示例如下:
results = collection.find({'gender': "male"}) print(results) for result in results: print(result)
運(yùn)行結(jié)果如下:
<pymongo.cursor.Cursor object at 0x0BDF8210>
{'_id': ObjectId('614be85f1cc0a98d6f034de7'), 'name': 'tigeriaf', 'gender': 'male'}
{'_id': ObjectId('614beb3ad0f17d253e2ef81c'), 'name': 'zhangsan', 'gender': 'male'}
{'_id': ObjectId('614beb3ad0f17d253e2ef81d'), 'name': 'lisi', 'gender': 'male'}
返回結(jié)果是Cursor
類(lèi)型,我們可以遍歷取到所有的結(jié)果。
6、統(tǒng)計(jì)查詢(xún)
可以調(diào)用count()
方法來(lái)統(tǒng)計(jì)查詢(xún)結(jié)果的條數(shù)。
count = collection.find({'gender': "male"}).count() print(count)
7、結(jié)果排序
可以調(diào)用sort()方法對(duì)查詢(xún)的數(shù)據(jù)進(jìn)行排序。
results = collection.find().sort('name', pymongo.ASCENDING) for result in results: print(result)
運(yùn)行結(jié)果如下:
{'_id': ObjectId('614bf7fca5af6d1d46df0878'), 'name': 'lisi', 'gender': 'male', 'age': 24}
{'_id': ObjectId('614bf72ab1b973eae1b32fee'), 'name': 'tigeriaf', 'gender': 'male', 'age': 24}
{'_id': ObjectId('614bf7fca5af6d1d46df0879'), 'name': 'wangwu', 'gender': 'female', 'age': 24}
{'_id': ObjectId('614bf7fca5af6d1d46df0877'), 'name': 'zhangsan', 'gender': 'male', 'age': 25}
8、偏移
在某些情況下我們可能只想獲取某幾條數(shù)據(jù),可以使用skip()方法進(jìn)行偏移操作,比如skip(2)
,就忽略前2條數(shù)據(jù),得到第3條之后的數(shù)據(jù)。
results = collection.find().sort('name', pymongo.ASCENDING).skip(2) for result in results: print(result)
運(yùn)行結(jié)果如下:
{'_id': ObjectId('614bf7fca5af6d1d46df0879'), 'name': 'wangwu', 'gender': 'female', 'age': 24}
{'_id': ObjectId('614bf7fca5af6d1d46df0877'), 'name': 'zhangsan', 'gender': 'male', 'age': 25}
另外還可以使用limit()
方法限制結(jié)果個(gè)數(shù)。
results = collection.find().sort('name', pymongo.ASCENDING).skip(1).limit(2) for result in results: print(result)
運(yùn)行結(jié)果如下:
{'_id': ObjectId('614bf72ab1b973eae1b32fee'), 'name': 'tigeriaf', 'gender': 'male', 'age': 24}
{'_id': ObjectId('614bf7fca5af6d1d46df0879'), 'name': 'wangwu', 'gender': 'female', 'age': 24}
9、更新數(shù)據(jù)
可以使用update_one()
方法和update_many()
方法對(duì)數(shù)據(jù)進(jìn)行更新,update_one()
方法更新一條數(shù)據(jù),update_many()
方法更新多條數(shù)據(jù)。
condition = {'name': 'wangwu'} user = collection.find_one(condition) user['age'] += 1 result = collection.update_one(condition, {'$set': user}) print(result) print(result.matched_count, result.modified_count)
在這里調(diào)用了update_one()
方法修改name
為wangwu
的數(shù)據(jù),第二個(gè)參數(shù)需要使用$類(lèi)型操作符作為字典的鍵名,返回結(jié)果調(diào)用matched_count
和modified_count
屬性可以獲得匹配的數(shù)據(jù)條數(shù)和影響的數(shù)據(jù)條數(shù)。
運(yùn)行結(jié)果如下:
<pymongo.results.UpdateResult object at 0x0C96E738>
1 1
調(diào)用update_many()
方法會(huì)更新所有符合條件的數(shù)據(jù)。
condition = {'age': 24} result = collection.update_many(condition, {'$inc': {'age': 1}}) print(result) print(result.matched_count, result.modified_count)
上述代碼指定了查詢(xún)條件為age
等于24,然后更新條件為{'$inc': {'age': 1}}
,也就是age
加1。
<pymongo.results.UpdateResult object at 0x0CB628A0> 2 2
可以看到更新了多條數(shù)據(jù)。
10、刪除數(shù)據(jù)
可以使用delete_one()
方法和delete_many()
方法刪除數(shù)據(jù),delete_one()
方法刪除一條數(shù)據(jù),delete_many()
方法刪除多條數(shù)據(jù)。
result = collection.delete_one({'name': 'zhangsan'}) print(result.deleted_count) result = collection.delete_many({'gender': "male"}) print(result.deleted_count)
運(yùn)行結(jié)果如下:
1
2
delete_one()
刪除的是第一條符合條件的數(shù)據(jù),delete_many()
刪除的是所有符合條件的數(shù)據(jù)。
到此這篇關(guān)于Python
操作 MongoDB
講解詳細(xì)的文章就介紹到這了,更多相關(guān)Python
操作 MongoDB
內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。