MongoDB介紹及與Python互動
阿新 • • 發佈:2018-12-18
1.mongodb的官方文件
2.關係型和非關係型介紹
- 關係型 1.儲存資料需要提前建表建庫 2.可擴充套件性差,大資料下IO壓力大,表結構更改困難
- 非關係型 1.易擴充套件 2.大資料量,高效能 3.資料模型靈活,⽆需事先為要儲存的資料建⽴欄位, 隨時可以儲存⾃定義的資料格式
3.mongodb和python互動
3. 1 模組:pymongo
3.2 python互動下的增刪改查
增
- python程式碼部分
# 0. pip install pymongo # 1. 匯入模組 from pymongo import * # 2. 建立客戶端物件 client = MongoClient(host='127.0.0.1',port=27017) # 3.獲取mongo資料庫物件 db_01 = client.db_01 # 4. 資料庫操作 # 1> 增 db_01.mycoll.insert({"name":"zs","gender":"1","age":18})
- 終端驗證:
# 終端開啟服務端 sudo mongod # 新開終端開啟客戶端 mongo #客戶端部分 查詢結果部分 > show dbs db_01 0.000GB local 0.000GB > use db_01 switched to db db_01 > show collections mycoll > db.mycoll.find() { "_id" : ObjectId("5bd91dfc1d41c8d348e3c70e"), "age" : 18, "gender" : "1", "name" : "zs" }
[注意] 第一步操作需要耐心操作,可能出現的bug有:
1.Connection refused
解決方案:
2.終端出現Active: failed (Result: exit-code)
更新
- 程式碼部分
# 0. pip install pymongo # 1. 匯入模組 from pymongo import * # 2. 建立客戶端物件 client = MongoClient(host='127.0.0.1',port=27017) # 3.獲取mongo資料庫物件 db_01 = client.db_01 # 4. 資料庫操作 # 1> 增 db_01.mycoll.insert({"name":"zs","gender":"1","age":18}) # 2> 更新 db_01.mycoll.update( # 更新條件 { "age":18 }, # 更新內容 { "$set":{ "name":"程式設計師" } }, # multi=True )
- 驗證
> db.mycoll.find()
{ "_id" : ObjectId("5bd91dee1d41c8d2f5c859d7"), "gender" : "1", "age" : 18, "name" : "程式設計師" }
- 注意
如果將multi = True寫成如下情況,會出現TypeError: upsert must be True or False
# 2> 更新
db_01.mycoll.update(
...
{
"multi":"True"
}
)
綜上看出:每一部分前面程式碼基本一致,後續只寫該部分相對應的程式碼
查
# 3> 查
# 返回的是一個遊標,遊標可以使記憶體使用率下降
cursor = db_01.mycoll.find(
{
"age":{"$gte":18}
}
)
# 利用for in 循環遊標
for row in cursor:
print(row)
刪除
db_01.mycoll.remove(
{
"age":{"$lt":20}
}
)
清空資料
db_01.mycoll.remove({})