Python爬蟲(chóng)分享:數(shù)據(jù)庫(kù)中的騷操作MongoDB
時(shí)間:2022-05-06 12:33:01 | 來(lái)源:行業(yè)動(dòng)態(tài)
時(shí)間:2022-05-06 12:33:01 來(lái)源:行業(yè)動(dòng)態(tài)
MongoDB是一個(gè)非常強(qiáng)大的數(shù)據(jù)庫(kù),我們常常在度娘搜索一些關(guān)鍵詞或者提問(wèn)題,都是由一個(gè)非常大數(shù)據(jù)庫(kù),才能讓你們這么折騰。
什么是數(shù)據(jù)庫(kù),應(yīng)該是用來(lái)存儲(chǔ)數(shù)據(jù)的,而MongoDB是一個(gè)介于關(guān)系數(shù)據(jù)庫(kù)和非關(guān)系數(shù)據(jù)庫(kù)之間的產(chǎn)品,是非關(guān)系數(shù)據(jù)庫(kù)當(dāng)中功能最豐富,最像關(guān)系數(shù)據(jù)庫(kù)的。
其語(yǔ)法有點(diǎn)類(lèi)似于面向?qū)ο蟮牟樵?xún)語(yǔ)言,幾乎可以實(shí)現(xiàn)類(lèi)似關(guān)系數(shù)據(jù)庫(kù)單表查詢(xún)的絕大部分功能。
這篇文章,就會(huì)詳細(xì)講解MongoDB,快拿上你的小本本記下來(lái)哦~
連接MongoDB from pymongo import MongoClient
client = MongoClient('localhost',27017)
另一種方法是直接傳遞MongoDB的連接字符串,以 mongodb 開(kāi)頭。
client = pymongo.MongoClient('mongodb://127.0.0.1:27017/')
前面有說(shuō)過(guò)MongoDB是非常大的數(shù)據(jù)庫(kù),其中每個(gè)數(shù)據(jù)庫(kù)又包含許多集合,選擇數(shù)據(jù)庫(kù)有兩種方法,這兩種方法作用相同。
db = client.test # test數(shù)據(jù)庫(kù)
db = client['test']
添加數(shù)據(jù) 單條: # 插入一條數(shù)據(jù),并獲取返回結(jié)果
res = student.insert_one({"name":"老王"})
# 獲取插入之后該條數(shù)據(jù)的id
object_id = res.inserted_id
print(object_id)
多條: # 插入9條數(shù)據(jù)
res = student.insert_many([{"name":"name%d"%index} for index in range(1,10)])
# 獲取插入之后該9條數(shù)據(jù)的ids,object_ids為一個(gè)list
object_ids = res.inserted_ids
print(object_ids)
提供兩種插入數(shù)據(jù)方法,最終還是要結(jié)合程序本身而來(lái)。
查詢(xún)數(shù)據(jù) 既然知道怎么添加數(shù)據(jù),下面來(lái)聊一聊怎么去查詢(xún)呢?
我們可以使用 find_one() 或 find() 方法,注意其中 find_one() 得到的是單個(gè)數(shù)據(jù)結(jié)果,find() 返回的是一個(gè)生成器對(duì)象,請(qǐng)看下面:
result = collection.find_one({'name': 'Mike'})
print(type(result))
print(result)
這里我們查詢(xún)name為Mike的數(shù)據(jù),它的返回結(jié)果是字典類(lèi)型,運(yùn)行結(jié)果如下:
class 'dict'
{'_id': ObjectId('5932a80115c2606a59e8a049'), 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}
對(duì)于多條數(shù)據(jù)的查詢(xún),我們可以使用find()方法。例如,這里查找年齡為30的數(shù)據(jù),示例如下:
results = collection.find({'age': 30})
print(results)
for result in results:
print(result)
如果要查詢(xún)年齡大于30的數(shù)據(jù),則寫(xiě)法如下:
results = collection.find({'age': {'$gt': 320}})
更新數(shù)據(jù):
更新數(shù)據(jù)我們使用 update() 方法實(shí)現(xiàn),并指定更新的條件和需要更新的數(shù)據(jù)即可。
where = {'name':'Abc'}
res = p.find_one(where)
res['age'] = 25
result = p.update(where, res) # 推薦使用 update_one() 或 update_many()print(result)
刪除數(shù)據(jù) 刪除操作比較簡(jiǎn)單,直接調(diào)用remove()方法指定刪除的條件即可,此時(shí)符合條件的所有數(shù)據(jù)均會(huì)被刪除。示例如下:
result = collection.remove({'name': 'Kevin'})
print(result)
符號(hào)認(rèn)識(shí) 在MongoDB還有一些特定符號(hào)需要記住,以下小編已經(jīng)整理出來(lái)了,請(qǐng)看:
比較符號(hào): $lt
$gt
$lte =
$gte =
$eq =
$ne !=
邏輯符號(hào): $and 邏輯與 a == True and b == True
$or 邏輯或 a == True or b == True
$not 邏輯非 a != True
$nor 邏輯非或 a != True or b != True
關(guān)于MongoDB的分享就到這里了,想了解更多關(guān)于python知識(shí)的童鞋,歡迎來(lái)私信小編,加入我們python大家庭,還有老師教知識(shí)、解答難題哦~
關(guān)鍵詞:操作,數(shù)據(jù),爬蟲(chóng)