1. 程式人生 > 資料庫 >[python爬蟲之路day12]:基於爬蟲的mongodb資料庫的基本操作

[python爬蟲之路day12]:基於爬蟲的mongodb資料庫的基本操作

今天學習了mongodb資料庫的基本操作。
初步瞭解資料庫的爬蟲方面的簡單操作,記錄如下:

mongodb和mysql比較
在這裡插入圖片描述
三元素:
資料庫,集合,文件
在這裡插入圖片描述
1.db (當前資料庫)
2.show dbs
3.use zhihu
4.db.dropDatabase()
5.db.集合名.insert(value)
6.db.集合名.find() 加粗樣式
在這裡插入圖片描述
使用管理員模式執行cmd
明確以下命令:

mongod --config C:\folders\alwaysuse\skilllearn\MONGOALL\mongod.cfg --install
net start mongodb

net stop mongodb
db
show dbs
use zhihu
db.qa.insert({“sd”:“sdsa”})
show dbs
db.qa.find()
db.qa.dropDatabase() #刪除
python程式碼操作mongodb資料庫

import pymongo
#獲取連線pymongo的物件
client=pymongo.MongoClient("127.0.0.1",port=27017)
#獲取資料庫(如果沒有zhihu,也沒有關係,會建立)
db=client.zhihu
#獲取資料庫中的集合(也就是mysql的表)
collection=db.qa
#插入資料
 collection.insert_one({"username":"aaaa"})
# #插入多條資料
collection.insert_many([
     {"username":"222","age":"18"},{"username":"3f22","age":"28"}
 ])
#查詢所有資料find()
 cursor=collection.find()
 for s in cursor:
     print(s)
#查詢一條資料
result=collection.find_one({"age":"28"})
print(result)
#更新資料(一條,多條)
collection.update_one({"username":"222"},{"$set":{"username":"ccc"}})
collection.update_many({"username":"aaaa"},{"$set":{"username":"cccb"}})
#刪除資料
collection.delete_one({"username":"cccb"})
collection.delete_many({"username":"cccb"})