好的,要能將資料寫進MongoDB,首先我們需要先安裝MongoDB:
https://www.mongodb.com/try/download/community
請點選右方綠色的Download按鈕來執行安裝本地Server端的免費社群版本,
假設對於雲端版本有興趣的朋友,可以自行研究MongoDB Atlas或是像GCP 也有可以2G資料以內免費使用的Datastore。
安裝的同時,請確定Compassu也有一同被安裝以方便我們來確定DB的資料有被使用。
接著,我們可以將資料寫入DB了:
@app.route('/write',methods=[ "GET",'POST'])
def upload():
print("write to mongoDB")
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mylist = [
{ "name": "Amy", "address": "Apple st 652"},
{ "name": "Hannah", "address": "Mountain 21"},
{ "name": "Michael", "address": "Valley 345"},
{ "name": "Sandy", "address": "Ocean blvd 2"},
{ "name": "Betty", "address": "Green Grass 1"},
{ "name": "Richard", "address": "Sky st 331"},
{ "name": "Susan", "address": "One way 98"},
{ "name": "Vicky", "address": "Yellow Garden 2"},
{ "name": "Ben", "address": "Park Lane 38"},
{ "name": "William", "address": "Central st 954"},
{ "name": "Chuck", "address": "Main Road 989"},
{ "name": "Viola", "address": "Sideway 1633"}
]
mycol.insert_many(mylist)
return index()
打開Compass進行連線:
在左邊database點選mydatabase,collection點選customers以觀看寫入DB的結果。
至於pymongo其他的操作方式,可以參考W3school 的pymongo教學:
https://www.w3schools.com/python/python_mongodb_getstarted.asp
像是find_one()不加query,為尋找第一筆資料。
mycol.find(),為尋找所有資料。
也可以讓資料變為list型態。
x = mycol.find_one()
mycol.find()
member_List = list(mycol.find())
將上query來尋找特定資料:
myquery = { "address": "Park Lane 38" }
mydoc = mycol.find(myquery)
修改特定資料:
myquery = { "address": "Valley 345" }
newvalues = { "$set": { "address": "Canyon 123" } }
mycol.update_one(myquery, newvalues)
mycol.update_many(myquery, newvalues)
更新
為了防止injection攻擊,可以參考這篇文章: