pymongo直接使用pip安裝:pip install pymongo
from pymongo import MongoClient
mongo_conn = MongoClient(host='localhost', port=27017)
mongo_db = mongo_conn.get_database("test") # 指定數據庫
coll = mongo_db.get_collection("people") # 指定集合
new_people = {
'name': "小明", 'age': 13}
# 增加
coll.insert_one(new_people)
coll.insert_many([{
"name": "小紅", 'age': 11}, {
"name": "小藍", "age": 12}])
# 查詢
record = coll.find_one({
'name': "小明"})
# 修改
coll.update_one(record, {
"$set": {
"age": 22, '成績': 101}, # "$set"是固定寫法,後面字典裡的是覆蓋的新值
})
# 刪除
coll.delete_one({
"name": "小紅"})