Mongodb之pymongo
一 ,pymongo模块的下载与使用
首先需要安装
pip install pymongo
二,使用
使用方法与数据库操作基本相同
1,连接
import pymongo mongo_client = pymongo.MongoClient(host="127.0.0.1", port=27017) mongo_db = mongo_client["day117"]
2,查
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"))
3,增
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)
4,改
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)
5,删
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)