Python 和資料庫的連結有著各種套件的組合,大家最常用的應該就是PyMySQL/SQLAlchemy/python-psycopg2
MongoDB也不例外,它也有屬於自己的介接API可以用。
Pymongo
今天暫時把Flask 放下,我們來看看怎麼透過Python和MongoDB連線吧
查詢條件:名稱叫Annie的
from pymongo import MongoClient
import pandas as pd
# Requires the PyMongo package.
# https://api.mongodb.com/python/current
client = MongoClient('mongodb+srv://<dbuser>:<yourpassword>@flasktodolist.d4tcc.azure.mongodb.net/test?authSource=admin&replicaSet=atlas-2wj2av-shard-0&readPreference=primary&appname=MongoDB%20Compass&ssl=true')
filter={
'name': 'Annie'
}
maxTimeMS=1
result = client['firstmongo']['firstcollect'].find(
filter=filter,
max_time_ms=maxTimeMS
)
df=pd.Series(result)
ds=df[0]
print(ds)
執行完這個程式之後就可以得到我們要查詢的設定條件了.
插入
from pymongo import MongoClient
import pandas as pd
# Requires the PyMongo package.
# https://api.mongodb.com/python/current
client = MongoClient('mongodb+srv://<dbuser>:<yourpassword>@flasktodolist.d4tcc.azure.mongodb.net/test?authSource=admin&replicaSet=atlas-2wj2av-shard-0&readPreference=primary&appname=MongoDB%20Compass&ssl=true')
db=client['firstmongo']
collection = db['firstcollect']
emp_rec1 = {
"name":"Mr.yen",
"eid":24,
"location":"delhi"
}
maxTimeMS=1
rec_id1 = collection.insert_one(emp_rec1)
print("Data inserted with record ids",rec_id1)
# Printing the data inserted
cursor = collection.find()
for record in cursor:
print(record)
成功插入一筆資料到最末端嚕
對MongoDB的介紹大致上就到這裡告一段落,有什麼補充資料的,會再這篇再更新。
Day10 時間很快 走過三分之一啦.
今天資料參考來源
GeeksGeeks