爬蟲學習筆記5 mongoDB的簡單使用

2021-10-02 17:45:15 字數 2323 閱讀 1682

1.匯入pymongo

import pymongo
2.連線資料庫

連線資料庫,兩種方式,生成兩個連線資料庫物件:

#1.連線資料庫,兩種方式,生成兩個連線資料庫物件

client_1 = pymongo.mongoclient(

'mongodb://localhost:27017/'

)client_2 = pymongo.mongoclient(host=

'localhost'

,port=

27017

)

3.連線具體的某個資料庫:

#2.指定具體的資料庫,兩種方式,生成兩個資料庫物件

db_1 = client_1.test

db_2 = client_2[

'test'

]

4.指定集合,類似於關係型資料中的表

#3.指定集合,類似於關係型資料中的表

collection_1 = db_1.students

collection_2 = db_2[

'students'

]#這樣,便生成了乙個cllection物件

5.插入資料

#在mongodb中,每條資料其實都有乙個_id屬性來唯一標識,如果沒有顯式指定該屬性

#mongodb會自動產生乙個objectid型別的_id屬性,insert()方法會在執行後返回_id值

#字典形式

student1 =

student2 =

student3 =

result = collection_1.insert_many(

[student1,student2,student3]

)

6.查詢資料

#查詢

search_result = collection_1.find_one(

)#查詢年齡大於20的

search_result2 = collection_1.find(})

for item in search_result2:

print

(item)

print

(type

(search_result2)

)

7.統計查詢結果的數量

呼叫count()方法

#查詢結果的總數

count = collection.find(

).count

#符合某個條件的條數

count = collection.find(

).count(

)

8.排序

呼叫sort()方法,並在其中傳入排序的字段,以及公升降序標誌

sort_results = collection.find(

).sort(

'name'

,pymongo.ascending)

print

([sort_result[

'name'

]for sort_result in sort_results]

)

9.更新

指定更新的條件,和更新後的資料

condition =

student = collection.find_one(condition)

student[

'age']=

45result = collection.update(condition,student)

print

(result)

10.刪除

remove()方法或delete_one()/delete_many()方法

#刪除一條資料

result = collection.remove(

)result2 = collection.delete_one(

)#刪除所有符合條件的資料

result3 = collevtion.delete_many(

})

MongoDB學習筆記5 測試查詢效能

大規模資料匯入實驗 在上乙個實驗 中,我們測試了匯入資料的效能,簡單總結一下測試方法 1.schema 每行資料三個字段,日期 id和當日流量,都是長整型 2.index inventory.create index date ascending id ascending unique false,...

Mongodb的學習筆記

mongodb是乙個高效能,開源,無模式的文件型資料庫,是當前nosql資料庫中比較熱門的一種。它在許多場景下可用於替代傳統的關係型資料庫或鍵 值儲存方式。mongo使用c 開發。mongo的官方 位址是 讀者可以在此獲得更詳細的資訊。小插曲 什麼是nosql?nosql,全稱是 not only ...

mongoDB的學習筆記

基本概念 1 文件 對應關聯式資料庫的行,也就是一條記錄。它比關聯式資料庫的行的功能要強大,更像是是某個具體的物件。文件以一種map的形式展現出來,當然value可以是任意的型別,也可以繼續是乙個文件 遞迴的定義 2 集合 對應關聯式資料庫的表。但是它又是無模式的,即文件不要求一致。基本操作 1 顯...