首先須要安裝數據庫
pip install pymongo
使用方法與數據庫操做基本相同spa
import pymongo mongo_client = pymongo.MongoClient(host="127.0.0.1", port=27017) mongo_db = mongo_client["day117"]
res = mongo_db.sado.find() print(res) # <pymongo.cursor.Cursor object at 0x0000028DEAAD03C8> 相似生成器 for data in res: print(data) res = mongo_db.sado.find_one({"name": "sado"}) print(res) print(res.get("_id"))
res = mongo_db.sado.insert_one({"who":"sado", "content":"今每天氣怎麼樣?", "datatime": time.time()}) # 插入單條 res = mongo_db.sado.insert_one({"who":"ai", "content":"請問要查詢哪所城市?", "datatime": time.time()}) print(res, res.inserted_id) res = mongo_db.sado.insert_many([{}, {}, {}]) # 插入多條 print(res, res.inserted_ids)
res = mongo_db.sado.update_one({"name": "sado"}, {"$set": {"age": 21}}) print(res, res.modified_count) res = mongo_db.sado.update_many({"age": {"$gte": 18}}, {"$set": {"age": 23}}) print(res, res.modified_count)
res = mongo_db.sado.delete_one({"$or": [{"name": "sado"}, {"name":"sola"}]}) print(res, res.deleted_count) res = mongo_db.sado.delete_many({}) # 刪除全部數據 print(res, res.deleted_count)