pymongo 的使用实例(超细)
MongoDB存儲
? ? ? ? 在這里我們來看一下Python3下MongoDB的存儲操作,在本節(jié)開始之前請確保你已經(jīng)安裝好了MongoDB并啟動了其服務(wù),另外安裝好了Python的PyMongo庫。
連接MongoDB
? ? ? ? 連接MongoDB我們需要使用PyMongo庫里面的MongoClient,一般來說傳入MongoDB的IP及端口即可,第一個參數(shù)為地址host,第二個參數(shù)為端口port,端口如果不傳默認(rèn)是27017。
import pymongo from pymongo import MongoClient#client = MongoClient(host='localhost', port=270171) conn = MongoClient("127.0.0.1", 27017)這樣我們就可以創(chuàng)建一個MongoDB的連接對象了。另外MongoClient的第一個參數(shù)host還可以直接傳MongoDB的連接字符串,以mongodb開頭,
例如:client = MongoClient('mongodb://localhost:27017/')可以達(dá)到同樣的連接效果。
?
指定數(shù)據(jù)庫
MongoDB中還分為一個個數(shù)據(jù)庫,我們接下來的一步就是指定要操作哪個數(shù)據(jù)庫,在這里我以test數(shù)據(jù)庫為例進(jìn)行說明,所以下一步我們需要在程序中指定要使用的數(shù)據(jù)庫。
db = conn.beeswarm # 調(diào)用client的test屬性即可返回test數(shù)據(jù)庫,當(dāng)然也可以這樣來指定: db = client['test'] # 兩種方式是等價的。?
指定集合,插入數(shù)據(jù)(創(chuàng)建數(shù)據(jù)庫表)
MongoDB的每個數(shù)據(jù)庫又包含了許多集合Collection,也就類似與關(guān)系型數(shù)據(jù)庫中的表,下一步我們需要指定要操作的集合,在這里我們指定一個集合名稱為students,學(xué)生集合。還是和指定數(shù)據(jù)庫類似,指定集合也有兩種方式。
collection = db.baituser collection = db['students'] # 插入數(shù)據(jù),接下來我們便可以進(jìn)行數(shù)據(jù)插入了,對于students這個Collection,我們新建一條學(xué)生數(shù)據(jù),以字典的形式表示:baituser = {"username":"johnny", "password":"password"} result = collection.insert_one(baituser) print "插入結(jié)果", result baituser = {"username":"julia", "password":"qweasd"} result = collection.insert_one(baituser) print "插入結(jié)果", result # 在這里我們指定了學(xué)生的學(xué)號、姓名、年齡和性別,然后接下來直接調(diào)用collection的insert()方法即可插入數(shù)據(jù)。 # 在MongoDB中,每條數(shù)據(jù)其實(shí)都有一個_id屬性來唯一標(biāo)識,如果沒有顯式指明_id,MongoDB會自動產(chǎn)生一個ObjectId類型的_id屬性。 # insert()方法會在執(zhí)行后返回的_id值。# 運(yùn)行結(jié)果: # # 5932a68615c2606814c91f3d # 當(dāng)然我們也可以同時插入多條數(shù)據(jù),只需要以列表形式傳遞即可,示例如下:""" 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) """ # 返回的結(jié)果是對應(yīng)的_id的集合,運(yùn)行結(jié)果: # [ObjectId('5932a80115c2606a59e8a048'), ObjectId('5932a80115c2606a59e8a049')] # 實(shí)際上在PyMongo 3.X版本中,insert()方法官方已經(jīng)不推薦使用了,當(dāng)然繼續(xù)使用也沒有什么問題, # 官方推薦使用insert_one()和insert_many()方法將插入單條和多條記錄分開。""" student = {'id': '20170101','name': 'Jordan','age': 20,'gender': 'male' }result = collection.insert_one(student) print(result) print(result.inserted_id) """ # 運(yùn)行結(jié)果: # <pymongo.results.InsertOneResult object at 0x10d68b558> # 5932ab0f15c2606f0c1cf6c5 # 返回結(jié)果和insert()方法不同,這次返回的是InsertOneResult對象,我們可以調(diào)用其inserted_id屬性獲取_id。# 對于insert_many()方法,我們可以將數(shù)據(jù)以列表形式傳遞即可,示例如下: """ 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,調(diào)用inserted_ids屬性可以獲取插入數(shù)據(jù)的_id列表,運(yùn)行結(jié)果: # <pymongo.results.InsertManyResult object at 0x101dea558> # [ObjectId('5932abf415c2607083d3b2ac'), ObjectId('5932abf415c2607083d3b2ad')]?
查詢
# 查詢,插入數(shù)據(jù)后我們可以利用find_one()或find()方法進(jìn)行查詢,find_one()查詢得到是單個結(jié)果,find()則返回多個結(jié)果。for abc in collection.find():print abc result = collection.find_one({"username":"johnny"}) print type(result) print result# 我們也可以直接根據(jù)ObjectId來查詢,這里需要使用bson庫里面的ObjectId。 from bson.objectid import ObjectIdresult = collection.find_one({'_id': ObjectId('5d132e975689095c2afec36e')}) print(result) # 其查詢結(jié)果依然是字典類型,運(yùn)行結(jié)果: # {' ObjectId('593278c115c2602667ec6bae'), 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'} # 當(dāng)然如果查詢_id':結(jié)果不存在則會返回None。# 對于多條數(shù)據(jù)的查詢,我們可以使用find()方法,例如在這里查找年齡為20的數(shù)據(jù),示例如下: #results = collection.find({'age': 20})# 如果要查詢年齡大于20的數(shù)據(jù),則寫法如下: #results = collection.find({'age': {'$gt': 20}}) # 在這里查詢的條件鍵值已經(jīng)不是單純的數(shù)字了,而是一個字典,其鍵名為比較符號$gt,意思是大于,鍵值為20,這樣便可以查詢出所有年齡大于20的數(shù)據(jù)在這里將比較符號歸納如下表:
符號含義示例
$lt小于{'age': {'$lt': 20}}
$gt大于{'age': {'$gt': 20}}
$lte小于等于{'age': {'$lte': 20}}
$gte大于等于{'age': {'$gte': 20}}
$ne不等于{'age': {'$ne': 20}}
$in在范圍內(nèi){'age': {'$in': [20, 23]}}
$nin不在范圍內(nèi){'age': {'$nin': [20, 23]}}
另外還可以進(jìn)行正則匹配查詢,例如查詢名字以M開頭的學(xué)生數(shù)據(jù),示例如下:
results = collection.find({'name': {'$regex': '^M.*'}})在這里將一些功能符號再歸類如下:
符號含義示例示例含義
$regex匹配正則{'name': {'$regex': '^M.*'}}name以M開頭
$exists屬性是否存在{'name': {'$exists': True}}name屬性存在
$type類型判斷{'age': {'$type': 'int'}}age的類型為int
$mod數(shù)字模操作{'age': {'$mod': [5, 0]}}年齡模5余0
$text文本查詢{'$text': {'$search': 'Mike'}}text類型的屬性中包含Mike字符串
$where高級條件查詢{'$where': 'obj.fans_count == obj.follows_count'}自身粉絲數(shù)等于關(guān)注數(shù)
這些操作的更詳細(xì)用法在可以在MongoDB官方文檔找到:
https://docs.mongodb.com/manual/reference/operator/query/
?
計數(shù)
# 要統(tǒng)計查詢結(jié)果有多少條數(shù)據(jù),可以調(diào)用count()方法,如統(tǒng)計所有數(shù)據(jù)條數(shù): count = collection.find().count() print "個數(shù)", count # 或者統(tǒng)計符合某個條件的數(shù)據(jù): count = collection.find({'age': 20}).count() print(count)?
排序
可以調(diào)用sort方法,傳入排序的字段及升降序標(biāo)志即可,示例如下:
調(diào)用 pymongo.ASCENDING()和pymongo.DESCENDING()來指定是按升降序進(jìn)行排序
?
偏移
可能想只取某幾個元素,在這里可以利用skip()方法偏移幾個位置,比如偏移2,就忽略前2個元素,得到第三個及以后的元素。
results = collection.find().sort('name', pymongo.ASCENDING).skip(2) print([result['name'] for result in results]) # 運(yùn)行結(jié)果: # ['Kevin', 'Mark', 'Mike']?
限制 limit
results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2) print([result['name'] for result in results])# 運(yùn)行結(jié)果: # ['Kevin', 'Mark'] # 如果不加limit()原本會返回三個結(jié)果,加了限制之后,會截取2個結(jié)果返回。值得注意的是,在數(shù)據(jù)庫數(shù)量非常龐大的時候,如千萬、億級別,最好不要使用大的偏移量來查詢數(shù)據(jù),很可能會導(dǎo)致內(nèi)存溢出,
可以使用類似find({'_id': {'$gt': ObjectId('593278c815c2602678bb2b8d')}}) 這樣的方法來查詢,記錄好上次查詢的_id。
?
更新
對于數(shù)據(jù)更新可以使用update()方法,指定更新的條件和更新后的數(shù)據(jù)即可,例如:
condition = {'name': 'Kevin'} student = collection.find_one(condition) student['age'] = 25 result = collection.update(condition, student) print(result) # 在這里我們將name為Kevin的數(shù)據(jù)的年齡進(jìn)行更新,首先指定查詢條件,然后將數(shù)據(jù)查詢出來,修改年齡, # 之后調(diào)用update方法將原條件和修改后的數(shù)據(jù)傳入,即可完成數(shù)據(jù)的更新。# 運(yùn)行結(jié)果: # {'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True} # 返回結(jié)果是字典形式,ok即代表執(zhí)行成功,nModified代表影響的數(shù)據(jù)條數(shù)。# 另外update()方法其實(shí)也是官方不推薦使用的方法,在這里也分了update_one()方法和update_many()方法,用法更加嚴(yán)格, # 第二個參數(shù)需要使用$類型操作符作為字典的鍵名,我們用示例感受一下。 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) # 在這里調(diào)用了update_one方法,第二個參數(shù)不能再直接傳入修改后的字典,而是需要使用{'$set': student}這樣的形式, # 其返回結(jié)果是UpdateResult類型,然后調(diào)用matched_count和modified_count屬性分別可以獲得匹配的數(shù)據(jù)條數(shù)和影響的數(shù)據(jù)條數(shù)。# 運(yùn)行結(jié)果: # # <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}},執(zhí)行之后會講第一條符合條件的數(shù)據(jù)年齡加1。# 運(yùn)行結(jié)果: # # <pymongo.results.UpdateResult object at 0x10b8874c8> # 1 1 # 可以看到匹配條數(shù)為1條,影響條數(shù)也為1條。# 如果調(diào)用update_many()方法,則會將所有符合條件的數(shù)據(jù)都更新,示例如下: condition = {'age': {'$gt': 20}} result = collection.update_many(condition, {'$inc': {'age': 1}}) print(result) print(result.matched_count, result.modified_count)# 這時候匹配條數(shù)就不再為1條了,運(yùn)行結(jié)果如下: # # <pymongo.results.UpdateResult object at 0x10c6384c8> # 3 3 # 可以看到這時所有匹配到的數(shù)據(jù)都會被更新。?
刪除
刪除操作比較簡單,直接調(diào)用remove()方法指定刪除的條件即可,符合條件的所有數(shù)據(jù)均會被刪除,示例如下:
result = collection.remove({'name': 'Kevin'}) print(result)# 運(yùn)行結(jié)果: # # {'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)# 運(yùn)行結(jié)果: # # <pymongo.results.DeleteResult object at 0x10e6ba4c8> # 1 # 4 # delete_one()即刪除第一條符合條件的數(shù)據(jù),delete_many()即刪除所有符合條件的數(shù)據(jù),返回結(jié)果是DeleteResult類型, # 可以調(diào)用deleted_count屬性獲取刪除的數(shù)據(jù)條數(shù)。?
更多
另外PyMongo還提供了一些組合方法,如find_one_and_delete()、find_one_and_replace()、find_one_and_update(),
就是查找后刪除、替換、更新操作,用法與上述方法基本一致。
?
另外還可以對索引進(jìn)行操作,如create_index()、create_indexes()、drop_index()等。
?
詳細(xì)用法可以參見官方文檔:http://api.mongodb.com/python/current/api/pymongo/collection.html
另外還有對數(shù)據(jù)庫、集合本身以及其他的一些操作,在這不再一一講解,可以參見
官方文檔:http://api.mongodb.com/python/current/api/pymongo/
?
?
?
源txt
#!/usr/bin/env python # -*- coding:utf-8 -*-""" MongoDB存儲在這里我們來看一下Python3下MongoDB的存儲操作,在本節(jié)開始之前請確保你已經(jīng)安裝好了MongoDB并啟動了其服務(wù),另外安裝好了Python的PyMongo庫。連接MongoDB連接MongoDB我們需要使用PyMongo庫里面的MongoClient,一般來說傳入MongoDB的IP及端口即可,第一個參數(shù)為地址host,第二個參數(shù)為端口port,端口如果不傳默認(rèn)是27017。 """import pymongo from pymongo import MongoClient#client = MongoClient(host='localhost', port=270171) conn = MongoClient("127.0.0.1", 27017)""" 這樣我們就可以創(chuàng)建一個MongoDB的連接對象了。另外MongoClient的第一個參數(shù)host還可以直接傳MongoDB的連接字符串,以mongodb開頭, 例如:client = MongoClient('mongodb://localhost:27017/')可以達(dá)到同樣的連接效果。 """# 指定數(shù)據(jù)庫 # MongoDB中還分為一個個數(shù)據(jù)庫,我們接下來的一步就是指定要操作哪個數(shù)據(jù)庫,在這里我以test數(shù)據(jù)庫為例進(jìn)行說明,所以下一步我們 # 需要在程序中指定要使用的數(shù)據(jù)庫。db = conn.beeswarm# 調(diào)用client的test屬性即可返回test數(shù)據(jù)庫,當(dāng)然也可以這樣來指定: # db = client['test'] # 兩種方式是等價的。# 指定集合 # MongoDB的每個數(shù)據(jù)庫又包含了許多集合Collection,也就類似與關(guān)系型數(shù)據(jù)庫中的表,下一步我們需要指定要操作的集合, # 在這里我們指定一個集合名稱為students,學(xué)生集合。還是和指定數(shù)據(jù)庫類似,指定集合也有兩種方式。collection = db.baituser # collection = db['students'] # 插入數(shù)據(jù),接下來我們便可以進(jìn)行數(shù)據(jù)插入了,對于students這個Collection,我們新建一條學(xué)生數(shù)據(jù),以字典的形式表示:baituser = {"username":"johnny", "password":"password"} #result = collection.insert_one(baituser) #print "插入結(jié)果", result baituser = {"username":"julia", "password":"qweasd"} #result = collection.insert_one(baituser) #print "插入結(jié)果", result # 在這里我們指定了學(xué)生的學(xué)號、姓名、年齡和性別,然后接下來直接調(diào)用collection的insert()方法即可插入數(shù)據(jù)。 # 在MongoDB中,每條數(shù)據(jù)其實(shí)都有一個_id屬性來唯一標(biāo)識,如果沒有顯式指明_id,MongoDB會自動產(chǎn)生一個ObjectId類型的_id屬性。 # insert()方法會在執(zhí)行后返回的_id值。# 運(yùn)行結(jié)果: # 5932a68615c2606814c91f3d # 當(dāng)然我們也可以同時插入多條數(shù)據(jù),只需要以列表形式傳遞即可,示例如下: """ 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) """ # 返回的結(jié)果是對應(yīng)的_id的集合,運(yùn)行結(jié)果: # [ObjectId('5932a80115c2606a59e8a048'), ObjectId('5932a80115c2606a59e8a049')] # 實(shí)際上在PyMongo 3.X版本中,insert()方法官方已經(jīng)不推薦使用了,當(dāng)然繼續(xù)使用也沒有什么問題, # 官方推薦使用insert_one()和insert_many()方法將插入單條和多條記錄分開。""" student = {'id': '20170101','name': 'Jordan','age': 20,'gender': 'male' }result = collection.insert_one(student) print(result) print(result.inserted_id) """ # 運(yùn)行結(jié)果: # <pymongo.results.InsertOneResult object at 0x10d68b558> # 5932ab0f15c2606f0c1cf6c5 # 返回結(jié)果和insert()方法不同,這次返回的是InsertOneResult對象,我們可以調(diào)用其inserted_id屬性獲取_id。# 對于insert_many()方法,我們可以將數(shù)據(jù)以列表形式傳遞即可,示例如下: """ 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,調(diào)用inserted_ids屬性可以獲取插入數(shù)據(jù)的_id列表,運(yùn)行結(jié)果: # <pymongo.results.InsertManyResult object at 0x101dea558> # [ObjectId('5932abf415c2607083d3b2ac'), ObjectId('5932abf415c2607083d3b2ad')]# 查詢,插入數(shù)據(jù)后我們可以利用find_one()或find()方法進(jìn)行查詢,find_one()查詢得到是單個結(jié)果,find()則返回多個結(jié)果。 for abc in collection.find():print abc result = collection.find_one({"username":"johnny"}) print type(result) print result# 我們也可以直接根據(jù)ObjectId來查詢,這里需要使用bson庫里面的ObjectId。 from bson.objectid import ObjectIdresult = collection.find_one({'_id': ObjectId('5d132e975689095c2afec36e')}) print(result) # 其查詢結(jié)果依然是字典類型,運(yùn)行結(jié)果: # {' ObjectId('593278c115c2602667ec6bae'), 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'} # 當(dāng)然如果查詢_id':結(jié)果不存在則會返回None。# 對于多條數(shù)據(jù)的查詢,我們可以使用find()方法,例如在這里查找年齡為20的數(shù)據(jù),示例如下: #results = collection.find({'age': 20})# 如果要查詢年齡大于20的數(shù)據(jù),則寫法如下: #results = collection.find({'age': {'$gt': 20}}) # 在這里查詢的條件鍵值已經(jīng)不是單純的數(shù)字了,而是一個字典,其鍵名為比較符號$gt,意思是大于,鍵值為20,這樣便可以查詢出所有年齡大于20的數(shù)據(jù)# 在這里將比較符號歸納如下表: """ 符號含義示例 $lt小于{'age': {'$lt': 20}} $gt大于{'age': {'$gt': 20}} $lte小于等于{'age': {'$lte': 20}} $gte大于等于{'age': {'$gte': 20}} $ne不等于{'age': {'$ne': 20}} $in在范圍內(nèi){'age': {'$in': [20, 23]}} $nin不在范圍內(nèi){'age': {'$nin': [20, 23]}} """# 另外還可以進(jìn)行正則匹配查詢,例如查詢名字以M開頭的學(xué)生數(shù)據(jù),示例如下: #results = collection.find({'name': {'$regex': '^M.*'}})# 在這里將一些功能符號再歸類如下: """ 符號含義示例示例含義 $regex匹配正則{'name': {'$regex': '^M.*'}}name以M開頭 $exists屬性是否存在{'name': {'$exists': True}}name屬性存在 $type類型判斷{'age': {'$type': 'int'}}age的類型為int $mod數(shù)字模操作{'age': {'$mod': [5, 0]}}年齡模5余0 $text文本查詢{'$text': {'$search': 'Mike'}}text類型的屬性中包含Mike字符串 $where高級條件查詢{'$where': 'obj.fans_count == obj.follows_count'}自身粉絲數(shù)等于關(guān)注數(shù) """# 這些操作的更詳細(xì)用法在可以在MongoDB官方文檔找到: # https://docs.mongodb.com/manual/reference/operator/query/# 計數(shù) # 要統(tǒng)計查詢結(jié)果有多少條數(shù)據(jù),可以調(diào)用count()方法,如統(tǒng)計所有數(shù)據(jù)條數(shù): count = collection.find().count() print "個數(shù)", count # 或者統(tǒng)計符合某個條件的數(shù)據(jù): #count = collection.find({'age': 20}).count() #print(count)# 排序 # 可以調(diào)用sort方法,傳入排序的字段及升降序標(biāo)志即可,示例如下: # 調(diào)用 pymongo.ASCENDING()和pymongo.DESCENDING()來指定是按升降序進(jìn)行排序 #results = collection.find().sort('name', pymongo.ASCENDING) #print([result['name'] for result in results]) # 運(yùn)行結(jié)果: # ['Harden', 'Jordan', 'Kevin', 'Mark', 'Mike']# 偏移,可能想只取某幾個元素,在這里可以利用skip()方法偏移幾個位置,比如偏移2,就忽略前2個元素,得到第三個及以后的元素。 #results = collection.find().sort('name', pymongo.ASCENDING).skip(2) #print([result['name'] for result in results]) # 運(yùn)行結(jié)果: # ['Kevin', 'Mark', 'Mike'] # 另外還可以用limit()方法指定要取的結(jié)果個數(shù),示例如下:#限制 limit #results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2) #print([result['name'] for result in results]) # 運(yùn)行結(jié)果: # ['Kevin', 'Mark'] # 如果不加limit()原本會返回三個結(jié)果,加了限制之后,會截取2個結(jié)果返回。# 值得注意的是,在數(shù)據(jù)庫數(shù)量非常龐大的時候,如千萬、億級別,最好不要使用大的偏移量來查詢數(shù)據(jù),很可能會導(dǎo)致內(nèi)存溢出, # 可以使用類似find({'_id': {'$gt': ObjectId('593278c815c2602678bb2b8d')}}) 這樣的方法來查詢,記錄好上次查詢的_id。# 更新 # 對于數(shù)據(jù)更新可以使用update()方法,指定更新的條件和更新后的數(shù)據(jù)即可,例如: #condition = {'name': 'Kevin'} #student = collection.find_one(condition) #student['age'] = 25 #result = collection.update(condition, student) #print(result) # 在這里我們將name為Kevin的數(shù)據(jù)的年齡進(jìn)行更新,首先指定查詢條件,然后將數(shù)據(jù)查詢出來,修改年齡, # 之后調(diào)用update方法將原條件和修改后的數(shù)據(jù)傳入,即可完成數(shù)據(jù)的更新。# 運(yùn)行結(jié)果: # {'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True} # 返回結(jié)果是字典形式,ok即代表執(zhí)行成功,nModified代表影響的數(shù)據(jù)條數(shù)。# 另外update()方法其實(shí)也是官方不推薦使用的方法,在這里也分了update_one()方法和update_many()方法,用法更加嚴(yán)格, # 第二個參數(shù)需要使用$類型操作符作為字典的鍵名,我們用示例感受一下。 #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) # 在這里調(diào)用了update_one方法,第二個參數(shù)不能再直接傳入修改后的字典,而是需要使用{'$set': student}這樣的形式, # 其返回結(jié)果是UpdateResult類型,然后調(diào)用matched_count和modified_count屬性分別可以獲得匹配的數(shù)據(jù)條數(shù)和影響的數(shù)據(jù)條數(shù)。# 運(yùn)行結(jié)果: # # <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}},執(zhí)行之后會講第一條符合條件的數(shù)據(jù)年齡加1。# 運(yùn)行結(jié)果: # # <pymongo.results.UpdateResult object at 0x10b8874c8> # 1 1 # 可以看到匹配條數(shù)為1條,影響條數(shù)也為1條。# 如果調(diào)用update_many()方法,則會將所有符合條件的數(shù)據(jù)都更新,示例如下: #condition = {'age': {'$gt': 20}} #result = collection.update_many(condition, {'$inc': {'age': 1}}) #print(result) #print(result.matched_count, result.modified_count)# 這時候匹配條數(shù)就不再為1條了,運(yùn)行結(jié)果如下: # # <pymongo.results.UpdateResult object at 0x10c6384c8> # 3 3 # 可以看到這時所有匹配到的數(shù)據(jù)都會被更新。# 刪除 # 刪除操作比較簡單,直接調(diào)用remove()方法指定刪除的條件即可,符合條件的所有數(shù)據(jù)均會被刪除,示例如下: #result = collection.remove({'name': 'Kevin'}) #print(result)# 運(yùn)行結(jié)果: # # {'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)# 運(yùn)行結(jié)果: # # <pymongo.results.DeleteResult object at 0x10e6ba4c8> # 1 # 4 # delete_one()即刪除第一條符合條件的數(shù)據(jù),delete_many()即刪除所有符合條件的數(shù)據(jù),返回結(jié)果是DeleteResult類型, # 可以調(diào)用deleted_count屬性獲取刪除的數(shù)據(jù)條數(shù)。# 更多 # 另外PyMongo還提供了一些組合方法,如find_one_and_delete()、find_one_and_replace()、find_one_and_update(), # 就是查找后刪除、替換、更新操作,用法與上述方法基本一致。# 另外還可以對索引進(jìn)行操作,如create_index()、create_indexes()、drop_index()等。# 詳細(xì)用法可以參見官方文檔:http://api.mongodb.com/python/current/api/pymongo/collection.html# 另外還有對數(shù)據(jù)庫、集合本身以及其他的一些操作,在這不再一一講解,可以參見 # 官方文檔:http://api.mongodb.com/python/current/api/pymongo/?
?
?
?
?
總結(jié)
以上是生活随笔為你收集整理的pymongo 的使用实例(超细)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Golang生成C动态库.so和静态库.
- 下一篇: 工控蜜罐Conpot部署和入门及高级演变